EML文件作为附件不是使用Python中的IMAP下载的?



我正在使用python中的IMAP库来读取一个工作文件的电子邮件收件箱,并且我已成功下载所有附件,但是当任何.eml文件作为附件出现时,我遇到了错误,请帮助我如何下载作为附件的EML文件。

为了从电子邮件中下载附件(如.png(,需要使用以下方法对有效负载进行解码: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 解析器? 你可以在这里找到 eml 解析器的手册。

您可以使用它:

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 - 请参阅库示例: https://github.com/ikvk/imap_tools/blob/master/examples/parse_eml_attachments.py

最新更新