代码之家  ›  专栏  ›  技术社区  ›  Lime

从电子邮件PHP中提取正文文本

  •  5
  • Lime  · 技术社区  · 14 年前

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

    一切正常,除了我不确定如何得到电子邮件的正文和标题。如果我做了 imap_body($connection,$message) 文本中包含与电子邮件附件等效的基64。

    我正在使用此函数获取附件。

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

    3 回复  |  直到 7 年前
        1
  •  20
  •   Lime    14 年前

    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;
    
        2
  •  2
  •   Jerry    8 年前

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

    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);
    
        3
  •  0
  •   Kailas    12 年前

    你也可以试试这些

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