我正在使用python 2.7并试图解析作为附件收件箱转发的电子邮件。我似乎无法解析附件消息的标题/电子邮件。我将其视为“ message / rfc822”,但是当我尝试对其进行解析时,它显示为空。
我通过生成器提取消息,它可以正常工作,如下所示:
res, data = self.imap_client.fetch(msg_id, '(RFC822)')
msg = email.message_from_string(data[0][1])
yield msg
然后将这个味精推入另一个函数中(通过walk()),我拉出附件
attachments = []
for part in msg.walk():
content_disposition = part.get('Content-Disposition', None)
if content_disposition:
attachments.append(Attachment(part, email_date))
return attachments
附件类如下:
class Attachment(object):
def __init__(self, attachment, email_date=None):
self.content_type = attachment.get_content_type()
self.attachment = attachment
fname = None
if self.content_type.startswith('message/'):
self.data = attachment.as_string()
fname = 'mail.eml'
else:
self.data = attachment.get_payload(decode=True)
try:
self.size = len(self.data)
except TypeError:
self.size = 0
if self.attachment.get_filename():
fname = self.attachment.get_filename().strip().replace(' ', '-')
self.name = re.sub(r'(?u)[^-\w.]', '', fname)
self.date = email_date
我尝试使用get_payload拉附件,并仅使用as_string()传递附件(如上所述),但无济于事。当我尝试解析电子邮件附件时,它没有任何数据:
if attachment.content_type == "message/rfc822":
msg = email.message_from_string(attachment.data)
print msg.get('Subject', None)