从 Google 邮件 API 解码 PHP 中的邮件附件

decoding mail attachments in PHP from Google Mail API

我正在使用 PHP 的 Google API 客户端库与 Gmail API 一起下载和处理一些电子邮件。

我收到的消息没有任何问题:

$optParamsGet = [];
$optParamsGet['format'] = 'full'; // Display message in payload
$message = $service->users_messages->get('me',$id,$optParamsGet);
$messagePayload = $message->getPayload();

然后我处理 getParts() 数组并得到第一个附件,这是一个没有名称的 .eml 文件

    [modelData:protected] => Array
        (
            [headers] => Array
                (
                    [0] => Array
                        (
                            [name] => Content-Type
                            [value] => message/rfc822
                        )
                    [1] => Array
                        (
                            [name] => Content-Disposition
                            [value] => attachment; creation-date="Fri, 24 Jul 2015 00:20:48 GMT"; modification-date="Fri, 24 Jul 2015 00:20:48 GMT"
                        )
                )
            [body] => Array
                (
                    [attachmentId] => ANGjdJ_TfJlMTssCNackUcQfT...mpppKiT8sSg
                    [size] => 37099
                )
        )

我的问题是:如何取消对 "attachmentId" 字符串的编码? 我以为是base64编码,结果命令

echo base64_decode($parts[1]->body->attachmentId);

只是吐出二进制数据。

我错过了什么?

attachmentId不是你附件的数据,而是附件的标识。要获取附件,您需要使用 messageId 和 attachmentId 进行一次请求,如下所示:

$attachmentData= $service->users_messages_attachments->get('me', $messageId, $attachmentId);

// Replace all '-' with '+' and '_' with '/' to make the url-safe
// base64 encoded data to regular base64.
$decodedData = strtr($attachmentData, array('-' => '+', '_' => '/'));