[英]Can't open downloaded attachments from 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);
解碼附件數據可能存在問題。 在將附件數據寫入文件之前,請嘗試在附件數據上使用此字符串替換。
$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);
您還需要使用消息有效內容的文件名部分加入要存儲文件的路徑。
我不是特別精通php,但在python中它將是以下的等價物:
path = ''.join([store_dir, part['filename']])
f = open(path, 'w')
f.write(file_data)
f.close()
file_data
是你解碼的地方(你的$data
)
在將其寫入文件之前,請嘗試以下方法解碼返回的附件數據。
$attachment_data = urlsafe_b64decode(utf8_encode($data->data));
為我工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.