在 php gmail api 中解码电子邮件正文?

Fel*_*les 2 php gmail-api

我正在尝试使用 Gmail API 阅读电子邮件正文

我使用的是 IMAP,但出于性能原因(在 IMAP 中阅读电子邮件需要花费大量时间),我必须转向速度相当快的 Gmail API。

问题是我试图解码 Body,IMAP 很简单,只需从 imap_fetchstructure 返回读取传输编码并使用适当的函数进行解码。(imap_qprint、imap_7bit 等)

对于 Gmail

        $message = $service->users_messages->get($user, $msg->id, ["format"=>"full"]);

        $payload = $message->getPayload();
        $mime = $payload->getMimeType();
        $body = $payload->getBody();
        $headers = $payload->getHeaders();
        $content = $body->getData();
        $decoded = base64_decode($content);
Run Code Online (Sandbox Code Playgroud)

变量 $contents 是 base64 中的主体,但如果我解码包含奇怪的字符,如 ?????? IMAP 没有发生这种情况。内容是纯文本 UTF-8,没有额外的部分或附件,只是纯文本。它也发生在 HTML 中。

这些是相关标题

     [{"name":"MIME-Version","value":"1.0"},
{"name":"Content-Type","value":"text\/plain; charset=utf-8"},
{"name":"Content-Transfer-Encoding","value":"quoted-printable"}]
Run Code Online (Sandbox Code Playgroud)

我认为问题在于正文是可引用打印的,但即使我在解码的 base64 上使用 imap_qprint 或 Quoted_printable_decode 这些奇怪的字符也会继续。

and*_*sen 5

我遇到了同样的问题……费利佩·莫拉莱斯(Felipe Morales)找到了解决方案……但要更明确一点:

从 API 响应中获取 base64-url-encoded 字符串,并通过此函数运行它:

function gmailBodyDecode($data) {
    $data = base64_decode(str_replace(array('-', '_'), array('+', '/'), $data)); 
    //from php.net/manual/es/function.base64-decode.php#118244

    $data = imap_qprint($data);
    return($data);
} 
Run Code Online (Sandbox Code Playgroud)

像冠军一样工作......

  • 效果很好!注释一,“impa_qprint”函数可以替换为php基线函数“quoted_printable_decode”。 (2认同)