传入消息的原始 MIME 树结构如下(使用email.iterators._structure(msg)
):
multipart/mixed
text/html (message)
application/octet-stream (attachment 1)
application/octet-stream (attachment 2)
通过 GMail 回复会产生以下结构:
multipart/alternative
text/plain
text/html
即他们没有我想象的那么聪明,只是丢弃附件(很好)并提供明确重组“引用内容”的文本和 HTML 版本。
我开始认为这也是我应该做的一切,只需回复一条简单的消息,因为在丢弃附件后,保留原始消息没有多大意义。
尽管如此,还是可以回答我原来的问题,因为无论如何我现在已经知道该怎么做了。
首先,将原始邮件中的所有附件替换为 text/plain 占位符:
import email
original = email.message_from_string( ... )
for part in original.walk():
if (part.get('Content-Disposition')
and part.get('Content-Disposition').startswith("attachment")):
part.set_type("text/plain")
part.set_payload("Attachment removed: %s (%s, %d bytes)"
%(part.get_filename(),
part.get_content_type(),
len(part.get_payload(decode=True))))
del part["Content-Disposition"]
del part["Content-Transfer-Encoding"]
然后创建回复消息:
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.message import MIMEMessage
new = MIMEMultipart("mixed")
body = MIMEMultipart("alternative")
body.attach( MIMEText("reply body text", "plain") )
body.attach( MIMEText("<html>reply body text</html>", "html") )
new.attach(body)
new["Message-ID"] = email.utils.make_msgid()
new["In-Reply-To"] = original["Message-ID"]
new["References"] = original["Message-ID"]
new["Subject"] = "Re: "+original["Subject"]
new["To"] = original["Reply-To"] or original["From"]
new["From"] = "me@mysite.com"
然后附加原始 MIME 消息对象并发送:
new.attach( MIMEMessage(original) )
s = smtplib.SMTP()
s.sendmail("me@mysite.com", [new["To"]], new.as_string())
s.quit()
生成的结构是:
multipart/mixed
multipart/alternative
text/plain
text/html
message/rfc822
multipart/mixed
text/html
text/plain
text/plain
或者使用 Django 更简单一些:
from django.core.mail import EmailMultiAlternatives
from email.mime.message import MIMEMessage
new = EmailMultiAlternatives("Re: "+original["Subject"],
"reply body text",
"me@mysite.com", # from
[original["Reply-To"] or original["From"]], # to
headers = {'Reply-To': "me@mysite.com",
"In-Reply-To": original["Message-ID"],
"References": original["Message-ID"]})
new.attach_alternative("<html>reply body text</html>", "text/html")
new.attach( MIMEMessage(original) ) # attach original message
new.send()
结果结束(至少在 GMail 中)将原始消息显示为“----转发的消息----”这不是我所追求的,但总体思路有效,我希望这个答案可以帮助尝试弄清楚如何摆弄 MIME 消息。