Python - eml 文件编辑

Python - eml file edit

我可以使用 mime-content 下载 eml 文件。我需要编辑这个 eml 文件并删除附件。我可以查找附件名称。如果我没理解错的话,首先是电子邮件 header、body,然后是附件。我需要有关如何从电子邮件 body 中删除附件的建议。

import email
from email import policy
from email.parser import BytesParser
with open('messag.eml', 'rb') as fp:  # select a specific email file
    msg = BytesParser(policy=policy.default).parse(fp)
    text = msg.get_body(preferencelist=('plain')).get_content()
    print(text)  # print the email content
    for attachment in attachments:
        fnam=attachment.get_filename()
        print(fnam) #print attachment name

术语“eml”并非严格意义上的well-defined,但您似乎想要处理标准 RFC5322(née 822)消息。

Python email 库在 Python 3.6 中进行了大修;您需要确保像您已经使用的那样使用现代 API(使用 policy 参数的)。删除附件的方法很简单,就是使用它的 clear() 方法,尽管您的代码一开始并没有正确获取附件。试试这个:

import email
from email import policy
from email.parser import BytesParser

with open('messag.eml', 'rb') as fp:  # select a specific email file
    msg = BytesParser(policy=policy.default).parse(fp)
    text = msg.get_body(preferencelist=('plain')).get_content()
    print(text)
    # Notice the iter_attachments() method
    for attachment in msg.iter_attachments():
        fnam = attachment.get_filename()
        print(fnam)
        # Remove this attachment
        attachment.clear()

with open('updated.eml', 'wb') as wp:
    wp.write(msg.as_bytes())

updated.eml 中的更新消息可能有一些 headers 重写,因为 Python 没有在所有 headers.[=15 中保留完全相同的间距等=]