【问题标题】:PHP email body decodingPHP电子邮件正文解码
【发布时间】:2014-05-15 09:14:16
【问题描述】:

在这里搜索和尝试解决方案很长一段时间后,我找不到解决问题的方法,尽管它确实修复了其中一条消息..

无论如何,我目前使用 PHP 中的 imap 函数来获取 Gmail 电子邮件,到目前为止它处理了 2 封邮件,但其他邮件仍然被编码或错误解码,我找不到我做的地方有问题,我当前的代码:

<?php

$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = '******@*******.com';
$password = '*******';


$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());


$emails = imap_search($inbox,'ALL');

$max = 5;
$i = 0;

if($emails) {

    $output = '';

    rsort($emails);

    foreach($emails as $email_number) {

        if($i === $max) {
            break;
        }

        $overview = imap_fetch_overview($inbox,$email_number, 0);
        $structure = imap_fetchstructure($inbox, $email_number);

        $output.= '<div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">';
        if (isset($overview[0]->subject)) {
            $output.= '<span class="subject">'.$overview[0]->subject.'</span> ';
        }else{
            $output.= '<span class="subject">No subject</span> ';
        }
        $output.= '<span class="from">'.$overview[0]->from.'</span>';
        $output.= '<span class="date">on '.$overview[0]->date.'</span>';
        $output.= '</div>';

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

        if(isset($structure->parts) && is_array($structure->parts) && isset($structure->parts[1])) {
            $part = $structure->parts[1];
            if($part->encoding == 3) {
                $message = imap_base64($message);
            }else if($part->encoding == 1) {
                $message = imap_8bit($message);
            }else{
                $message = imap_qprint($message);
            }
        }

        $output.= '<div class="body">'.utf8_encode($message).'</div>';
        $i++;
    }

    echo $output;
} 

imap_close($inbox);

?>

输出: http://www.mupload.nl/img/7pn51ldwpxj.png

非常感谢!

【问题讨论】:

  • 您忽略了内容传输编码。您的两条消息是 base64 编码的。
  • 不,那些不是。这些是二进制文件。第一个是 .gif 文件(参见 GIF89a 标头)。第二个是 zip 文件(PK 标头)。

标签: php encoding imap


【解决方案1】:

我正在使用 Gmail PHP SDK 打开电子邮件。
PHP Gmail Client Library

您不能只对正文进行 base64 解码,因为 Gmail base64 需要“清理”。如果只是使用base64_decode,你会发现body里还是满是奇怪的字符。

$body_data = strtr($parts[0]["modelData"]["body"]["data"], '-_', '+/=');
$message_body = base64_decode($body_data);

我从Stackoverflow 'Mark as read mail method'得到了这个base64解码的解决方案

【讨论】:

    【解决方案2】:

    您可能为这些消息选择了错误的正文部分。这些是二进制文件:一个是 GIF 文件(参见 GIF89 标头),另一个是 ZIP 文件(参见 PK 标头)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-28
      • 2020-12-23
      • 2018-07-28
      • 2018-12-01
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 2012-09-22
      相关资源
      最近更新 更多