Search code examples
python-3.xbase64imapemail-attachments

How to download imap email attachment with base64 content in python?


I am struggling to download one particular pdf file(having watermark) as an email attachment? I can send it to your email, if you give me your email address?

I tried below piece:-

        fp = open(mail.filePath, 'wb')
        body = mail.part.get_payload(decode = True)
        file_data = base64.encodestring(body).decode()
        file_data = file_data.encode('UTF-8')
        #file_data = base64.urlsafe_b64decode(mail.part.get_payload(decode=True).encode('UTF-8'))
        fp.write(file_data)
        fp.close()

Solution

  • Try to use high level lib.

    from imap_tools import MailBox
    
    # get all attachments from INBOX and save them to files
    with MailBox('imap.my.ru').login('acc', 'pwd', 'INBOX') as mailbox:
        for msg in mailbox.fetch():
            for att in msg.attachments:
                print(att.filename, att.content_type)
                with open('C:/1/{}'.format(att.filename), 'wb') as f:
                    f.write(att.payload)
    

    https://github.com/ikvk/imap_tools