PHP电子邮件正文解码

时间:2014-04-03 13:33:18

标签: php encoding imap

在这里搜索并尝试解决方案很长一段时间之后,我无法找到解决问题的方法,虽然它确实解决了其中一条消息..

无论如何,我目前正在使用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

非常感谢!

2 个答案:

答案 0 :(得分:1)

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

您无法对身体进行base64解码,因为Gmail base64需要进行清理&#34;。如果你只使用base64_decode,你会发现身体仍然充满了奇怪的字符。

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

我从Stackoverflow 'Mark as read mail method'

获得了base64解码的解决方案

答案 1 :(得分:0)

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