无法从 Gmail 获取 IMAP 中的电子邮件正文

Cannot get email body in IMAP from Gmail

我想阅读 GMail 的邮件正文。

我能够获取所有详细信息,例如发件人姓名、电子邮件和主题等,但不能获取电子邮件正文。

// Connect to gmail
$username = 'email';
$password = 'password';
/* connect to server */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
/* try to connect */
$inbox = imap_open($hostname, $username, $password) or die('Cannot connect to Gmail: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox, 'ALL');
/* if emails are returned, cycle through each... */
if ($emails) {
    /* begin output var */
    $output = '';
    /* put the newest emails on top */
    rsort($emails);
    /* for every email... */
    foreach ($emails as $email_number) {
        /* get information specific to this email */
        $overview = imap_fetch_overview($inbox, $email_number, 0);
        $message = imap_fetchbody($inbox, $email_number, "1.2");

        /* output the email header information */
        $output.= '<div class="toggler ' . ($overview[0]->seen ? 'read' : 'unread') . '">';
        $output.= '<span class="subject">' . $overview[0]->subject . '</span> ';
        $output.= '<span class="from">' . $overview[0]->from . '</span>';
        $output.= '<span class="date">on ' . $overview[0]->date . '</span>';
        $output.= '</div>';

        /* output the email body */
        $output.= '<div class="body">' . $message . '</div>';
    }

    echo $output;
}

我知道有特定的 Gmail API 可以做到这一点,但 IMAP 不应该工作吗?

来自 PHP 的 documentation 它说

(empty) - Entire message
0 - Message header
1 - MULTIPART/ALTERNATIVE
1.1 - TEXT/PLAIN
1.2 - TEXT/HTML
2 - MESSAGE/RFC822 (entire attached message)
2.0 - Attached message header
2.1 - TEXT/PLAIN
2.2 - TEXT/HTML
2.3 - file.ext

我试过$message = imap_fetchbody($inbox, $email_number, "1.2");$message = imap_fetchbody($inbox, $email_number, 1.2);

但是它 returns 空结果。

我也试过 $message = imap_fetchbody($inbox, $email_number, "2"); 但它 returns 损坏 HTML 与我在 Gmail 中收到的非常不同。

下车我不得不使用

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

正确传达信息。

我已经尝试并成功了

$message = quoted_printable_decode(imap_fetchbody($conn, $email_number, 1));