python - 通过 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图像也会出现同样的问题)
非常感谢,贾祖利
解决方案
正如预期的那样,这是一个编码问题,行
msg.add_header('Content-Transfer-Encoding', '7bit')
不应该在那里
推荐阅读
- ionic-framework - 在 Ionic 版本 4.10.3 上使用 Ionic Devapp 时出错
- regex - 正则表达式与 Python 3 匹配以下划线开头和结尾的单词
- c# - 删除文本中多行的制表符或空格
- c++ - C++ 计算器类给了我在多个 cpp 文件中分布的最低可能的 int?
- swift - Swift - 在使用 gcd 获得多个网络调用时遇到问题
- python - Numpy n-对角矩阵广播分解
- python - 如何找到与正则表达式匹配的所有单词?
- dataframe - 获取pyspark数据框中每一列的总和
- python - 为python中列表/元组中的每个数据调用API的最佳方法是什么?
- java - 在类名中使用非 ASCII 字符时编译错误