user1630350
user1630350

Reputation: 79

IMAP with python to download attachments

I have a instrument at work that emails me a file containing raw data, I can go into my email and download them easily enough but when I have multiple files (which it sends as multiple emails) it gets a bit tedious.

I'm looking at using python and imaplib to login to my email account, search for emails from a known email address within the past day or so and then download any attachments to a directory. So I thought a script might help here.

I've setup a gmail account and altered the settings so that I can connect using imap from a shell, however I'm lost as to where to go from here.

Could someone point me in the right direction as to what I need to do to make this happen.

Upvotes: 2

Views: 3571

Answers (1)

ratatatat
ratatatat

Reputation: 152

Here is a repository that is forked off imaplib (made compatible with Python3.6, did not test other versions)

https://github.com/christianwengert/mail

The following snippet checks all unseen messages, then returns their attachments:

server = IMAPClient(imap, use_uid=True, ssl=993)
server.login(username, password)
server.select_folder('INBOX')
message_ids = server.search([b'NOT', b'SEEN']) # UNSEEN
messages = server.fetch(message_ids, data=['ENVELOPE', 'BODYSTRUCTURE',  'RFC822.SIZE'])

for mid, content in messages.items():
    bodystructure = content[b'BODYSTRUCTURE']
    text, attachments = walk_parts(bodystructure, msgid=mid, server=server)

HTH

Upvotes: 1

Related Questions