[英]How to add pdf attachment in an existing eml file using Python?
[英]EML file as attachment is not downloading using IMAP in Python?
我在 python 中使用 IMAP 庫來讀取正在工作的電子郵件收件箱,我正在成功下載我的所有附件,但是當任何 .eml 文件作為附件出現時,我收到一個錯誤,請幫助我如何下載一個 eml 文件依戀。
有一點晚; 但是對於其他遇到相同問題的人,這里是解決方案。
為了從電子郵件下載附件(例如.png
,需要使用以下part.get_payload(decode=True).decode()
對有效負載進行解碼: part.get_payload(decode=True).decode()
。 但是,從文檔中:
如果消息是多部分的並且解碼標志為 True,則返回 None。
您看到的錯誤是由於.eml
文件是多部分消息引起的。 這些部分由頂層的message/rfc822
組成,其中包含所有電子郵件的詳細信息。 下面將是單部分消息,例如text/html
,其中包含電子郵件的文本等...
要將此文本下載到.html
或.txt
文件中,您需要.walk()
瀏覽.eml
文件的各個部分 - 就像您在原始電子郵件中下載.eml
附件時所做的那樣。
這是我的代碼片段:
if msg.is_multipart():
for part in msg.walk():
# extract content type of email
content_type = part.get_content_type()
content_disposition = str(part.get("Content-Disposition"))
if "attachment" in content_disposition:
if content_type == "message/rfc822":
# walk through the .eml attachment parts:
for eml_part in part.walk():
# find the content type of each part:
content_type = eml_part.get_content_type()
if content_type == "text/html": # this type is not multipart
body = eml_part.get_payload(decode=True).decode() # get_payload() can be decoded
# can do what you need with the decoded body.
# in this case extract text and save to .txt or .html
else: .....
我對在這里發帖很陌生,所以如果混淆,請原諒我。
也許您需要使用 EML Parser? 您可以在此處找到 eml-parser 的手冊。
你可以使用它:
def _read(self):
"""Reads all emails and get attachments.
Returns:
Attachments.
"""
self.mail.list()
self.mail.select(self.select)
self.mail.uid('search', None, 'ALL')
self.uids = self.data[0].split()
self.content_length = len(self.uids)
self.attachments = []
for uid in self.uids:
self.result, self.email_data = self.mail.uid(
'fetch', uid, '(RFC822)')
self.raw_email = self.email_data[0][1]
self.raw_email_string = self.raw_email.decode('utf-8')
self.parsed_email = email.message_from_bytes(self.raw_email)
for part in self.parsed_email.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get_content_type() not in ['text/html', 'text/plain']:
self.attachments.append({
'name':
part.get_filename(),
'content_type':
part.get_content_type(),
'bytes':
part.get_payload(decode=True)
})
self.result = {'attachments': self.attachments}
return self.result
嘗試使用我的高級 imap 庫:
https://github.com/ikvk/imap_tools
from imap_tools import MailBox, MailMessage
# get .eml files attached to email messages from INBOX
with MailBox('imap.mail.com').login('test@mail.com', 'password', 'INBOX') as mailbox:
for message in mailbox.fetch():
for att in message.attachments:
if '.eml' in att.filename:
print(att.filename, len(att.payload))
您也可以就地解析 .eml - 請參閱 lib 示例: https : //github.com/ikvk/imap_tools/blob/master/examples/parse_eml_attachments.py
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.