我可以使用mime内容下载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发布于 2021-11-05 10:19:33
术语"eml“没有严格定义,但看起来您想要处理标准的RFC5322 (née 822)消息。
Python库在Python3.6中进行了一次大修;您需要确保使用现代的email,就像您已经使用的那样(使用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中的更新消息可能会重写一些标头,因为在所有标头中都没有保留相同的间距等等。
https://stackoverflow.com/questions/69850757
复制相似问题