如何使用 Python imaplib 回复电子邮件并包含原始消息?
我目前正在使用 imaplib
从服务器并处理内容和附件。
我想回复带有状态/错误消息的消息,并链接到我的网站上生成的内容(如果可以处理)。这应该包括原始消息,但应删除所有附件(附件很大),最好仅用文件名/大小替换它们。
由于我已经在遍历 MIME 消息部分,因此我假设我需要做的是构建一个新的 MIME 消息树,其中包含原始消息的副本并删除/替换附件节点。
在我开始这条道路之前,我希望有人能给我一些建议。有什么库函数可以做到这一点吗?我应该遵守什么标准行为?
我目前知道/正在使用 imaplib
、smtplib
和 email
模块,但可能错过了其中明显的东西。它也在 Django 中运行,因此可以使用 django.core.email 中的任何内容(如果这样更容易的话)。
I'm currently using imaplib
to fetch email messages from a server and process the contents and attachments.
I'd like to reply to the messages with a status/error message and links to the resulting generated content on my site if they can be processed. This should include the original message but should drop any attachments (which will be large) and preferably replace them with just their filenames/sizes.
Since I'm already walking the MIME message parts, I'm assuming what I need to do is build a new MIME message tree containing a copy of the original message and delete/replace the attachment nodes.
Before I start down that path, I was hoping someone can give me some tips. Is there any kind of library function to do this? Any kind of standard behavior I should stick to?
I currently know of/am using the imaplib
, smtplib
and email
modules and but may have missed something obvious in there. This is running in Django too, so can use anything in django.core.email
if that makes it easier.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
传入消息的原始 MIME 树结构如下(使用
email.iterators._struct(msg)
):通过 GMail 回复会产生以下结构:
即,他们没有我那么聪明我想,只需丢弃附件(很好)并提供明确重组“引用内容”的文本和 HTML 版本。
我开始认为这也是我应该做的,只需回复一条简单的消息,因为在丢弃附件后,保留原始消息没有多大意义。
不过,也许还是回答我原来的问题,因为我现在已经知道该怎么做了。
首先,用文本/纯占位符替换原始消息中的所有附件:
然后创建回复消息:
然后附加原始 MIME 消息对象并发送:
结果结构为:
或者使用 Django 会更简单:
结果结束(在GMail 至少)将原始消息显示为“----转发的消息----”,这并不完全是我想要的,但总体思路是有效的,我希望这个答案可以帮助那些试图弄清楚如何摆弄的人与 MIME 消息。
The original MIME tree structure of the incoming message is as follows (using
email.iterators._structure(msg)
):Replying via GMail results in the following structure:
I.e. they aren't being as smart as I thought, just discarding the attachments (good) and providing text and HTML versions that explicitly restructure the "quoted content."
I'm beginning to think that's all I should do too, just reply with a simple message as after discarding the attachments there's not much point in keeping the original message.
Still, might as well answer my original question since I've figured out how to now anyway.
First, replace all the attachments in the original message with text/plain placeholders:
Then create a reply message:
Then attach the original MIME message object and send:
The resulting structure is:
Or it's a bit simpler using Django:
The result ends (in GMail at least) showing the original message as "---- Forwarded message ----" which isn't quite what I was after, but the general idea works and I hope this answer helps someone trying to figure out how to fiddle with MIME messages.