传入消息的原始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版本来明确重组“引用的内容”。
我开始认为这也是我应该做的,只是用一条简单的消息答复,因为丢弃附件后,保留原始消息没有多大意义。
尽管如此,还是应该回答我最初的问题,因为无论如何我现在已经弄清楚了如何解决。
首先,将原始邮件中的所有附件替换为文本/纯文本占位符:
import emailoriginal = 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(depre=True)))) del part["Content-Disposition"] del part["Content-Transfer-Encoding"]
然后创建一个回复消息:
from email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.message import MIMEMessagenew = 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 EmailMultiAlternativesfrom email.mime.message import MIMEMessagenew = 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 messagenew.send()
结果结束(至少在GMail中),将原始消息显示为“
----转发的消息----”,这与我所追求的不完全相同,但是总体思路可行,我希望这个答案可以帮助某人尝试弄清楚如何摆弄MIME消息。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)