[英]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.