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

7
我目前正在使用imap流来获取收件箱中的电子邮件。
除了不确定如何获取电子邮件的正文和标题之外,一切都很正常。如果我执行imap_body($connection,$message),则附件的base64编码会包含在文本中。
我目前正在使用此函数来获取附件。 http://www.electrictoolbox.com/function-extract-email-attachments-php-imap/
3个回答

26

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个小时后,我终于找到了可行的示例。 - Himanshu Yadav
2
那个 1.2 是什么意思? - pguardiario
1
@pguardiario 我不确定,但如果你点击上面的链接可能会有所帮助。我相信我是通过反复试验找到了解决方案的。 - Lime
@pguardiario 这是您想要检索的多部分 MIME 文档的一部分。例如,text/plain、text/html... - Alex W

10

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

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
这个应该被接受。它适用于比当前被接受的答案更多类型的电子邮件。谢谢! - Parampal Pooni

0

你也可以尝试这些

content-type:text/html

$message = imap_fetchbody($inbox,$email_number, 2);

content-type:plaintext/text

$message = imap_fetchbody($inbox,$email_number, 1);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接