Skip to content

Instantly share code, notes, and snippets.

@FiloSottile
Created March 12, 2012 13:52
Show Gist options
  • Star 26 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save FiloSottile/2022075 to your computer and use it in GitHub Desktop.
Save FiloSottile/2022075 to your computer and use it in GitHub Desktop.
Simple script to dump an IMAP folder into eml files
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import imaplib
import getpass
import argparse
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('-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()
gmail = imaplib.IMAP4_SSL(args.host)
gmail.login(args.username, getpass.getpass())
gmail.select(args.remote_folder)
typ, data = gmail.search(None, 'ALL')
for num in data[0].split():
typ, data = gmail.fetch(num, '(RFC822)')
f = open('%s/%s.eml' %(args.local_folder, num), 'w')
print >> f, data[0][1]
gmail.close()
gmail.logout()
@spacecdr
Copy link

Interesting... is it possible for you dump the whole imap mailbox? (even with sub-folders and email on them)

@Fusoricius
Copy link

Thanks for this. It helped me build a quick spamassassin trainer that reads from my IMAP mailbox.

@petersteier
Copy link

unfortunately, on 2018 says: imaplib.error:
command SEARCH illegal in state AUTH, only allowed in states SELECTED

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment