IMAP with python to download attachments

白昼怎懂夜的黑 提交于 2020-07-22 21:33:30

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/43997978/imap-with-python-to-download-attachments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!