我可以使用 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
uj5u.com熱心網友回復:
術語“eml”沒有嚴格定義,但看起來您想要處理標準 RFC5322 (née 822) 訊息。
Pythonemail庫在 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 不會在所有標題中保留完全相同的間距等。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/352358.html
