用Python发送带有HTML和纯文本的电子邮件并附带PDF附件

4
我将尝试发送一封电子邮件,附带一个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附件正在覆盖电子邮件正文。
1个回答

10

这样的消息应该具有更复杂的结构。消息本身包含两个“顶级”MIME部分,并具有内容类型“multipart/mixed”。第一个MIME部分的类型为“multipart/alternative”,其中包含两个子部分,一个为纯文本,另一个为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()
你可以尝试在你喜欢的邮件程序(邮件用户代理)中打开消息的“源代码视图”并查看自己(在Thunderbird中按Ctrl-U)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接