How to save email attached to another using python smtplib?

I am using python imaplib to download and save attachments in email. But when there is an email with an attached file in the email, x.get_payload () has Nonetype. I think these types of emails are sent using some email clients. Since the file name is missing, I tried to change the file name in the header and then "Content-Disposition". The renamed file opens and when I try to write this file using

fp.write(part.get_payload(decode=True))

he says a line or buffer is expected, but Nonetype is found.

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

I deleted decode = True and I got a list of objects

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

I tried editing the file name in case the email was found as an attachment.

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 > ]

?

+4
1

. [< mail.message.Message instance at 0x7fe5e09aa248 > ] - mail.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 .

+3

All Articles