Can't open downloaded attachments from Gmail A

2019-02-27 12:19发布

I feel like I'm missing something stupid...

I'm using the PHP SDK for the new Gmail API to fetch an attachment from an email. I can get the attachment content, but unless it's a text file, I can't open the file after it's been saved. If the attachment is a PDF, it won't render. If it's an excel file, it won't open.

What am I doing wrong?

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

3条回答
疯言疯语
2楼-- · 2019-02-27 12:36

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

查看更多
beautiful°
3楼-- · 2019-02-27 12:44

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

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

worked for me.

查看更多
看我几分像从前
4楼-- · 2019-02-27 12:49

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)

查看更多
登录 后发表回答