如何使用python smtplib保存附加在另一个电子邮件中的电子邮件?

时间:2014-11-18 04:59:18

标签: python email email-attachments imaplib

我正在使用python imaplib下载并保存电子邮件中的附件。但是当有一封带附件的电子邮件作为另一封电子邮件时,x.get_payload()属于Nonetype。我认为这些类型的邮件是使用一些电子邮件客户端发送的。由于缺少文件名,我尝试更改标题中的文件名,后跟'Content-Disposition'。当我尝试使用

写入该文件时,重命名的文件将被打开
fp.write(part.get_payload(decode=True))

它表示预期的字符串或缓冲区,但发现了Nonetype。

>>>x.get_payload()
[<email.message.Message instance at 0x7f834eefa0e0>]
>>>type(part.get_payload())
<type 'list'>
>>>type(part.get_payload(decode=True))
<type 'NoneType'>

我删除了decode = True,我得到了一个对象列表

x.get_payload()[0]
<email.message.Message instance at 0x7f834eefa0e0>

我尝试编辑文件名以防电子邮件被发现为附件。

if part.get('Content-Disposition'): 
    attachment = str(part.get_filename()) #get filename
    if attachment == 'None':
        attachment = 'somename.mail'
        attachment = self.autorename(attachment)#append (no: of occurences) to filename eg:filename(1) in case file exists
        x.add_header('Content-Disposition', 'attachment', filename=attachment)
        attachedmail = 1

 if attachedmail == 1:
     fp.write(str(x.get_payload()))
 else:
     fp.write(x.get_payload(decode=True)) #write contents to the opened file

并且该文件包含对象名称文件内容,如下所示

[ < email.message.Message instance at 0x7fe5e09aa248 > ]

如何将这些附加电子邮件的内容写入文件?

1 个答案:

答案 0 :(得分:3)

我自己解决了。如[&lt; email.message.Message instance at 0x7fe5e09aa248&gt; ]是email.message.Message实例的列表,每个实例都有.as_string()方法。在我的例子中,将.as_string()的内容写入文件帮助我将整个标题数据(包括嵌入的附件)提取到文件中。然后我逐行检查了文件,并根据编码和文件类型保存了内容。

>>>x.get_payload()
[<email.message.Message instance at 0x7f834eefa0e0>]
>>>fp=open('header','wb')
>>>fp.write(x.get_payload()[0].as_string())
>>>fp.close()
>>>file_as_list = []
>>>fp=open('header','rb')
>>>file_as_list = fp.readlines()
>>>fp.close()

然后检查文件中的每一行

for x in file_as_list:
    if 'Content-Transfer-Encoding: quoted-printable' in x:
        print 'qp encoded data found!'
    if 'Content-Transfer-Encoding: base64' in x:
        print 'base64 encoded data found!'  

可以跳过表示内联(嵌入)附件的编码数据,因为imaplib已经捕获了它。