【问题标题】:Extract body text from Email PHP从电子邮件 PHP 中提取正文文本
【发布时间】:2011-05-15 10:13:38
【问题描述】:

我目前正在使用 imap 流从收件箱中获取电子邮件。

一切正常,除了我不确定如何获取电子邮件的正文和标题。如果我这样做imap_body($connection,$message),则文本中包含等效于电子邮件附件的 base 64。

我目前正在使用这个功能来获取附件。

http://www.electrictoolbox.com/function-extract-email-attachments-php-imap/

【问题讨论】:

    标签: php imap


    【解决方案1】:

    使用 php imap 的功能并不好玩。此页面上的用户解释了与获取电子邮件的不一致之处:http://php.net/manual/en/function.imap-fetchbody.php#89002

    使用他的有用信息,我创建了一种获取电子邮件正文的可靠方法。

    $bodyText = imap_fetchbody($connection,$emailnumber,1.2);
    if(!strlen($bodyText)>0){
        $bodyText = imap_fetchbody($connection,$emailnumber,1);
    }
    $subject = imap_headerinfo($connection,$i);
    $subject = $subject->subject;
    
    echo $subject."\n".$bodyText;
    

    【讨论】:

    • 非常感谢。谷歌搜索 4 小时后,我找到了工作示例。
    • 1.2 是什么意思?
    • @pguardiario 我不知道,尽管如果您单击上面的链接可能会有所帮助。我相信我通过反复试验找到了解决方案。
    • @pguardiario 这是您要检索的多部分 MIME 文档的一部分。例如。文本/纯文本,文本/html...
    【解决方案2】:

    你也可以试试这些

    content-type:text/html
    
    $message = imap_fetchbody($inbox,$email_number, 2);
    
    content-type:plaintext/text
    
    $message = imap_fetchbody($inbox,$email_number, 1);
    

    【讨论】:

      【解决方案3】:

      我的解决方案(适用于所有类型和字符集):

      function format_html($str) {
          // Convertit tous les caractères éligibles en entités HTML en convertissant les codes ASCII 10 en $lf
          $str = htmlentities($str, ENT_COMPAT, "UTF-8");
          $str = str_replace(chr(10), "<br>", $str);
          return $str;
      }
      
      
      // Start
      
      $obj_structure = imap_fetchstructure($imapLink, $obj_mail->msgno);
      
      // Recherche de la section contenant le corps du message et extraction du contenu
      $obj_section = $obj_structure;
      $section = "1";
      for ($i = 0 ; $i < 10 ; $i++) {
          if ($obj_section->type == 0) {
              break;
          } else {
              $obj_section = $obj_section->parts[0];
              $section.= ($i > 0 ? ".1" : "");
          }
      }
      $text = imap_fetchbody($imapLink, $obj_mail->msgno, $section);
      // Décodage éventuel
      if ($obj_section->encoding == 3) {
          $text = imap_base64($text);
      } else if ($obj_section->encoding == 4) {
          $text = imap_qprint($text);
      }
      // Encodage éventuel
      foreach ($obj_section->parameters as $obj_param) {
          if (($obj_param->attribute == "charset") && (mb_strtoupper($obj_param->value) != "UTF-8")) {
              $text = utf8_encode($text);
              break;
          }
      }
      
      // End
      print format_html($text);
      

      【讨论】:

      • 这个应该被接受。适用于比当前接受的答案更多类型的电子邮件。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-12
      • 1970-01-01
      • 2012-01-03
      • 1970-01-01
      • 2011-01-09
      • 2011-10-09
      • 2014-03-23
      相关资源
      最近更新 更多