【问题标题】:Python - eml file editPython - eml 文件编辑
【发布时间】:2021-12-19 08:41:09
【问题描述】:

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

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

【问题讨论】:

标签: python email mime-types eml


【解决方案1】:

术语“eml”没有严格定义,但看起来您想要处理标准 RFC5322(née 822)消息。

Python email 库在 Python 3.6 中进行了大修;您需要确保使用现代 API,就像您已经使用的那样(使用 policy 参数的 API)。删除附件的方法是简单地使用其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 中的更新消息可能会重写一些标头,因为 Python 不会在所有标头中保留完全相同的间距等。

【讨论】:

  • 这就是它的工作原理。唯一的问题是有空的txt文件而不是附件,但我仍然关心电子邮件的大小。
  • 不确定你的意思。如果您有没有规定结构的消息,您可能希望设置一个不修改它们的条件。
猜你喜欢
  • 2019-12-26
  • 2019-05-16
  • 2019-12-11
  • 1970-01-01
  • 1970-01-01
  • 2015-10-02
  • 2012-01-19
  • 2015-06-13
相关资源
最近更新 更多