Skip to content

Instantly share code, notes, and snippets.

@polo2ro
Forked from FiloSottile/dump-imap.py
Last active February 9, 2024 22:32
Show Gist options
  • Save polo2ro/e142e164a327ee576321 to your computer and use it in GitHub Desktop.
Save polo2ro/e142e164a327ee576321 to your computer and use it in GitHub Desktop.
Simple script to dump an IMAP folder into eml files, store email using the message-id
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import imaplib
import argparse
import email
import re
argparser = argparse.ArgumentParser(description="Dump a IMAP folder into .eml files")
argparser.add_argument('-s', dest='host', help="IMAP host, like imap.gmail.com", required=True)
argparser.add_argument('-u', dest='username', help="IMAP username", required=True)
argparser.add_argument('-p', dest='password', help="IMAP password", required=True)
argparser.add_argument('-r', dest='remote_folder', help="Remote folder to download", default='INBOX')
argparser.add_argument('-l', dest='local_folder', help="Local folder where to save .eml files", default='.')
args = argparser.parse_args()
mailbox = imaplib.IMAP4_SSL(args.host)
mailbox.login(args.username, args.password)
mailbox.select(args.remote_folder)
typ, data = mailbox.search(None, 'ALL')
for num in data[0].split():
typ, data = mailbox.fetch(num, '(RFC822)')
for response_part in data:
if isinstance(response_part, tuple):
msg = email.message_from_string(response_part[1])
if msg['Message-Id']:
filename = re.sub('[^a-zA-Z0-9_\-\.()\s]+', '', msg['Message-Id'])
f = open('%s/%s.eml' %(args.local_folder, filename), 'w')
print >> f, data[0][1]
else:
print 'No Message-Id for %s' %(msg['Subject'])
mailbox.close()
mailbox.logout()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment