无法从Gmail API打开下载的附件

rhu*_*uff 2 php email-attachments gmail-api

我觉得我错过了一些愚蠢的事......

我正在使用PHP SDK为新的Gmail API提取电子邮件中的附件.我可以获得附件内容,但除非它是文本文件,否则我无法在保存文件后打开它.如果附件是PDF,则不会呈现.如果是excel文件,则无法打开.

我究竟做错了什么?

// this works; I get the attachment body, etc
$data = $g->gmail->users_messages_attachments->get($email_account, $email_message_id, $p->getBody()->getAttachmentId());

$fh = fopen(DOC_ROOT."/file.pdf", "w+");
fwrite($fh, base64_decode($data->data));
fclose($fh);
Run Code Online (Sandbox Code Playgroud)

Art*_*son 11

解码附件数据可能存在问题.在将附件数据写入文件之前,请尝试在附件数据上使用此字符串替换.

  
    $data = $g->gmail->users_messages_attachments->get($email_account, $email_message_id, $p->getBody()->getAttachmentId());

    // Converting to standard RFC 4648 base64-encoding
    // see http://en.wikipedia.org/wiki/Base64#Implementations_and_history
    $data = strtr($data, array('-' => '+', '_' => '/'));

    $fh = fopen(DOC_ROOT."/file.pdf", "w+");
    fwrite($fh, base64_decode($data->data));
    fclose($fh);