Skip to content

Instantly share code, notes, and snippets.

@marcocox
Last active October 5, 2022 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcocox/3dfae6b1a0a546ad820b558d4e1c8e9e to your computer and use it in GitHub Desktop.
Save marcocox/3dfae6b1a0a546ad820b558d4e1c8e9e to your computer and use it in GitHub Desktop.
Python script to download CSV file attachments from an IMAP mailbox
# Download all csv file attachments from an IMAP mailbox, save in working dir, delete email(s) afterwards.
# IMPORTANT: all emails are deleted, even the ones that do not have (csv) attachments.
# Usage: python3 download_mailbox_csv_attachments.py {imap_host} {username} {password}
import imaplib, email, os, sys, random
if len(sys.argv) != 4:
print('Invalid number of arguments')
exit(1)
host = sys.argv[1]
user = sys.argv[2]
pw = sys.argv[3]
imaplib.IMAP4.debug = imaplib.IMAP4_SSL.debug = 1
con = imaplib.IMAP4_SSL(host, 993)
con.login(user, pw)
con.select()
typ, data = con.search(None, '(ALL)')
for num in data[0].split():
typ, data = con.fetch(num, '(RFC822)')
try:
msg = email.message_from_bytes(data[0][1])
except:
continue
for part in msg.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
if not filename.lower().endswith('.csv'):
continue
data = part.get_payload(decode=True)
if not data:
continue
dest = '%d_%s' % (random.randint(0,10000), filename.lower())
print(dest)
f = open(dest, 'wb')
f.write(data)
f.close()
con.store(num, '+FLAGS', '\\Deleted')
con.expunge()
con.close()
con.logout()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment