If you’re trying to extract e-mail attachments via Python script, you may be in for a ride. I tried quite a few different solutions and after even playing with recursion in Python to traverse n layers of mime-wrappers, finally stumbled across this library: Imbox
The examples are all pretty self-explanatory. If you want a system service that checks for new mails at regular intervals, you may want to condense a few concepts. Here’s my solution, if you’re into minimalist turn-key examples without any traps or safetynets.
It checks for unread emails, marks them as read, downloads their attachments and finally, optionally, deletes them. You can loop over the main part while True
: , with a sleep somewhere, obvs. 🙂
from imbox import Imbox
# intialize
dl_folder = '/tmp'
m_host = 'server.domain'
m_username = 'user'
m_password = 'pass'
# main part
mail = Imbox(m_host, username=m_username, password=m_password, ssl=True, ssl_context=None, starttls=False)
messages = mail.messages(unread=True) # defaults to inbox
for (uid, message) in messages:
mail.mark_seen(uid)
for idx, attachment in enumerate(message.attachments):
att_fn = attachment.get('filename')
dl_path = f"{dl_folder}/{att_fn}"
with open(dl_path, "wb") as fp:
fp.write(attachment.get('content').read())
mail.delete(uid) # optional
mail.logout()
Leave a Reply