传入消息的原始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 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"] = "[email protected]"
然后附原始MIME消息对象和发送
首先,原始邮件文本/纯占位符代替所有的附件:
new.attach(MIMEMessage(original))
s = smtplib.SMTP()
s.sendmail("[email protected]", [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",
"[email protected]", # from
[original["Reply-To"] or original["From"]], # to
headers = {'Reply-To': "[email protected]",
"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中至少)示出原始消息为“----转发消息----”,这ISN”这与我之后的工作非常相似,但总的想法很有效,我希望这个答案可以帮助有人试图弄清楚如何处理MIME消息。
“我希望这个答案可以帮助有人试图弄清楚如何摆弄MIME信息。” -----它确实如此。谢谢汤姆! – aniketd 2016-05-23 10:26:52