首页 > 解决方案 > 通过 Gmail API 发送后损坏的 pdf

问题描述

我目前正在尝试通过 Gmail API 发送 pdf 附件,但我收到的文件似乎已损坏。这是我用来创建电子邮件的代码。

message_out = MIMEMultipart()
content_type, encoding = mimetypes.guess_type(attachment)
if content_type is None or encoding is not None:
    content_type = 'application/octet-stream'
main_type, sub_type = content_type.split('/', 1)  


with open(attachment, 'rb') as fp:
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
filename = os.path.basename(attachment)
msg.add_header('Content-Disposition', 'attachment', filename=filename)
msg.add_header('Content-Type', main_type, name=filename)
msg.add_header('Content-Transfer-Encoding', '7bit')
email.encoders.encode_base64(msg)
message_out.attach(msg)

return {'raw': base64.urlsafe_b64encode(message_out.as_bytes()).decode()}

当我尝试打开附件时,我会收到“无法加载 PDF 文档”。我想这与编码有关,但我不知道为什么,我认为 email.encoders 会解决我所有的问题。(png图像也会出现同样的问题)

非常感谢,贾祖利

标签: pythonemailencodinggmailattachment

解决方案


正如预期的那样,这是一个编码问题,行

msg.add_header('Content-Transfer-Encoding', '7bit')

不应该在那里


推荐阅读