Can't open downloaded attachments from Gmail API

笑着哭i 提交于 2019-12-02 02:18:12

There may be an issue with decoding the attachment data. Try using this string replace on the attachment data before writing it to a file.

  
    $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);

You also need to join the path of where you want to store your file with the filename part of the message payload.

I'm not particularly well versed in php, but in python it would be the equivilent of:

path = ''.join([store_dir, part['filename']])
f = open(path, 'w')
f.write(file_data)
f.close()

Where the file_data is what you have decoded (your $data)

Amit Aggarwal

Try the following to decode returned attachment data before writing it to file.

$attachment_data = urlsafe_b64decode(utf8_encode($data->data));

worked for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!