如何在PHP中使用IMAP函数以HTML模式获取邮件正文内容


How to use IMAP function(s) in PHP to get the mail body content in HTML mode?

摘要

我曾尝试使用imap_fetchbodyimap_body函数以HTML模式获取电子邮件内容,但失败了。下面是我尝试过的PHP代码。你能告诉我错误在哪里吗?顺便说一句,邮件可能是用其他语言写的,所以请注意字符集。

代码

imap_fetchbody:

<?php
/* connect to server */
$mail_server="mail.example.com";
$mail_link="{{$mail_server}:143/imap/notls}" ;
$mail_user="user@mail.example.com";
$mail_pass="password";
/* try to connect */
$inbox = imap_open($mail_link, $mail_user, $mail_pass) or die('Cannot connect: ' . imap_last_error());
/* email number */
$mail_number = 1;       //The number of the mail (The first mail)
/* fetch the email content in HTML mode */
$message = imap_fetchbody($inbox,$mail_number,1.2);
/* output the email body */
$output= '<div class="body">'.$message.'</div>';
echo $output;
/* close the connection */
imap_close($inbox);
?>

imap_body:

<?php
/* connect to server */
$mail_server="mail.example.com";
$mail_link="{{$mail_server}:143/imap/notls}" ;
$mail_user="user@mail.example.com";
$mail_pass="password";
/* try to connect */
$inbox = imap_open($mail_link, $mail_user, $mail_pass) or die('Cannot connect: ' . imap_last_error());
/* email number */
$mail_number = 1;       //The number of the mail (The first mail)
/* fetch the email content in HTML mode */
$message = imap_qprint(imap_body($inbox,$mail_number));
/* output the email body */
$output= '<div class="body">'.$message.'</div>';
echo $output;
/* close the connection */
imap_close($inbox);
?>

后记

除了imap_fetchbodyimap_body之外,还有其他IMAP函数可以在HTML模式下获取电子邮件内容吗?

以下是我用来从gmail获取电子邮件并阅读它们的一些代码:

$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox,'UNSEEN');
/* if emails are returned, cycle through each... */
if ($emails)
{
    /* put the newest emails on top */
    rsort($emails);
    /* for every email... */
    foreach ($emails as $email_number)
    {
        $emailMessage = new EmailMessage($inbox, $email_number);
        $emailMessage->fetch();
        $dom = new DOMDocument;
        libxml_use_internal_errors(true);
        $dom->loadHTML($emailMessage->bodyHTML);
    }
}

EmailMessage类可在此处找到:http://www.electrictoolbox.com/php-email-message-class-extracting-attachments/