[英]Python - eml file edit
我可以使用 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
术语“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 不会在所有标头中保留完全相同的间距等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.