2010-11-01 74 views
18

我有一个电子邮件多部分邮件对象,我想将该电子邮件中的附件转换为python文件对象。这可能吗?如果可能的话,我应该研究Python中的哪些方法或类来完成这样的任务?获取邮件附件到python文件对象

+0

你至今读哪一部分Python库吗?你有没有看过pop或imap库? – 2010-11-01 10:12:44

+0

我只看着email.message.Message和mimetools.Message。好吧,我会读入pop和imail,看看我能用它做什么。 – 2010-11-01 10:18:18

回答

47

我真的不明白“email multipart message object”的含义。你的意思是属于email.message.Message类的对象吗?

如果这就是你的意思,那很简单。在多部分消息中,get_payload方法返回消息部分的列表(每个消息部分本身都是一个Message对象)。您可以遍历这些部分并检查它们的属性:例如,get_content_type方法返回该部分的MIME类型,get_filename方法返回该部分的文件名(如果在消息中指定了该文件)。然后,当您找到正确的信息部分时,您可以拨打get_payload(decode=True)获取解码的内容。

>>> import email 
>>> msg = email.message_from_file(open('message.txt')) 
>>> len(msg.get_payload()) 
2 
>>> attachment = msg.get_payload()[1] 
>>> attachment.get_content_type() 
'image/png' 
>>> open('attachment.png', 'wb').write(attachment.get_payload(decode=True)) 

如果你编程方式提取您收到电子邮件中的附件,你可能要采取防范病毒和木马的防范措施。特别是,你可能只应该提取你知道的MIME类型安全的附件,并且你可能想要选择你自己的文件名,或者至少清除get_filename的输出。

+0

这很好。谢谢。 – 2010-11-06 20:53:58

+1

HTML邮件通常在页脚中有图像,这些图像也作为附件发送。您可以通过查看Content-Disposition来区分这些内容与“真实”附件:内嵌图像以“inline”开头,而实际附件以“attachment”开头。没有获取内容处置的方法,但如果您只对实际附件感兴趣,则可以调用part.get('Content-Disposition')。startswith('attachment')。 – jrial 2017-06-25 15:21:45

9

这里是工作的解决方案,消息形式IMAP服务器

self.imap.select() 
typ, data = self.imap.uid('SEARCH', 'ALL') 
msgs = data[0].split() 
print "Found {0} msgs".format(len(msgs)) 

for uid in msgs: 
    typ, s = self.imap.uid('FETCH', uid, '(RFC822)') 
    mail = email.message_from_string(s[0][1]) 

    print "From: {0}, Subject: {1}, Date: {2}\n".format(mail["From"], mail["Subject"], mail["Date"]) 

    if mail.is_multipart(): 
     print 'multipart' 
     for part in mail.walk(): 
      ctype = part.get_content_type() 
      if ctype in ['image/jpeg', 'image/png']: 
       open(part.get_filename(), 'wb').write(part.get_payload(decode=True))