![](/img/trans.png)
[英]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.