根据电子邮件包的文档,尝试使用以下代码。
文档显示了一些 png 图像作为附件发送到电子邮件的示例,这是有效的。但是,代码看起来(如果我错了请纠正我)与文件类型无关,所以我用pdf试了一下。
#!/usr/bin/env python3
# encoding: utf-8
# Create the container email message.
msg = EmailMessage()
msg['Subject'] = 'Our Family Reunion'
msg['From'] = SENDER
msg['To'] = receiver
with open(file=os.path.join(RESOURCE_DIR, BODY_FILE)) as file:
msg.set_content(file.read())
filename='sample.png' # This opens at the receiver mailbox
filename='sample.pdf' # This seems corrupted at the recipient mailbox
path=filename
ctype, encoding = mimetypes.guess_type(url=path)
maintype, subtype = ctype.split(sep='/', maxsplit=1)
with open(path, 'rb') as fp:
msg.add_attachment(fp.read(),
maintype=maintype,
subtype=subtype,
filename=os.path.basename(p=filename))
# Send the email via our own SMTP server.
with smtplib.SMTP(host='smtp.gmail.com', port=587) as session:
session.starttls() # Enable security, otherwise Gmail refuses connection
session.login(user=SENDER, password=PASSWORD)
session.send_message(msg=msg, from_addr=msg['From'], to_addrs=msg['To'])
带有 pdf 附件的电子邮件已送达,但附件似乎已损坏,我的 pdf 阅读器 (evince) 无法打开它。甚至
md5sum
散列摘要在原始和收到的 pdf 文件之间也不同。这是我的技术栈
那么代码真的与文件类型无关吗?如果不是,pdf 需要哪些特殊注意事项?至少,是否有可能涵盖所有 pdf(无论编码、字体、有无嵌入图像等)?
链接 示例 pdf(传输和接收)和 thunderbird 中的电子邮件源。