python - 在 Python 中发送带有 HTML+plain_text 电子邮件的 PDF 附件

标签 python email email-attachments

我正在尝试发送一个 PDF 附件,其中的电子邮件正文总结了 PDF 文件的内容。电子邮件正文采用 HTML 和纯文本格式。

我正在使用以下代码构建电子邮件电子邮件对象:

#Part A
logging.debug("   Building standard email with HTML and Plain Text")
msg = MIMEMultipart("alternative")
msg.attach(MIMEText(email_obj.attachments["plain_text"], "plain", _charset="utf-8"))
msg.attach(MIMEText(email_obj.attachments["html_text"], "html", _charset="utf-8"))

#Part B
logging.debug("   Adding PDF report")
pdf_part = MIMEApplication(base64.decodestring(email_obj.attachments["pdf_report"]), "pdf")
pdf_part.add_header('Content-Disposition', 'attachment', filename="pdf_report.pdf")
logging.debug("   Attaching PDF report")
msg.attach(pdf_part)

我的问题是,如果我附加 PDF,我的电子邮件正文就会消失。如果我注释掉附加 PDF 的代码(B 部分),则会出现电子邮件正文。

除非我弄错了,否则我的 PDF 附件似乎覆盖了电子邮件正文。

最佳答案

这样的消息应该有更复杂的结构。消息本身包含两个“顶级”MIME 部分,内容类型为“multipart/mixed”。这些 MIME 部分中的第一个具有“多部分/替代”类型,有两个子部分,一个用于纯文本,另一个用于 HTML。第二个主要部分是PDF附件

pdfAttachment = MIMEApplication(pdf, _subtype = "pdf")
pdfAttachment.add_header('content-disposition', 'attachment', filename = ('utf-8', '', 'payment.pdf'))
text = MIMEMultipart('alternative')
text.attach(MIMEText("Some plain text", "plain", _charset="utf-8"))
text.attach(MIMEText("<html><head>Some HTML text</head><body><h1>Some HTML Text</h1> Another line of text</body></html>", "html", _charset="utf-8"))
message = MIMEMultipart('mixed')
message.attach(text)
message.attach(pdfAttachment)
message['Subject'] = 'Test multipart message'
f = open("message.msg", "wb")
f.write(bytes(message.as_string(), 'utf-8'))
f.close()

您可以尝试在您最喜欢的邮件程序(邮件用户代理)中打开消息的“源代码 View ”并查看您自己(在 Thunderbird 中为 Ctrl-U)

关于python - 在 Python 中发送带有 HTML+plain_text 电子邮件的 PDF 附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22789379/

相关文章:

php - 将数组内的查询结果放入 PHP 电子邮件附件

python - 使用 sqlalchemy 和 pyodbc 在 MS SQL Server 上获取查询的返回行

c# - 检索电子邮件的 AlternateView

android - 如何从 Android 模拟器替换/卸载电子邮件应用程序

python - 电子邮件中的尾随等号 (=)

html - 如何在 iOS 中的电子邮件的 HTML 正文中嵌入图像

javascript - 多个文件作为电子邮件附件上传

python - 如何在列表中创建列表,其中每个 future 列表都由列表中的空格分隔

python - 在python中提取子字符串

python - 如何让机器人框架等到数据出现在MySQL表上才继续测试用例执行