IMAP Message Downloader/Archiver

With this Python script you can archive e-mails from IMAP accounts locally. All emails from each IMAP folder in the account are dumped into .eml files. Each IMAP folder is outputted into a sub-folder of the same name.

Pretty handy to archive emails prior to deleting an account.

Download

Copy the script below or download it here: imap-dl.py.zip

#!/usr/bin/env python

import sys, os
import imaplib
import getpass

#
# IMAP account settings
#
imap_server = 'imapserver.com'
account = "user@imapserver.com"
out_dir = '/path/to/the/imap-output'

#
# Export Emails
#
passwd = getpass.getpass()

def process_mailbox(M,finaloutput):
    """
    Dump all emails in the folder to files in output directory.
    """

    rv, data = M.search(None, "ALL")
    if rv != 'OK':
        print "No messages found!"
        return
    for num in data[0].split():
        rv, data = M.fetch(num, '(RFC822)')
        if rv != 'OK':
            print "ERROR getting message", num
            return
        print "Writing message ", num
        directory = '%s/%s' %(out_dir, finaloutput)
        if not os.path.exists(directory):
            os.makedirs(directory)
        f = open('%s/%s/%s.eml' %(out_dir, finaloutput, num), 'wb')
        f.write(data[0][1])
        f.close()

def main():
    M = imaplib.IMAP4_SSL(imap_server)
    M.login(account, passwd)
    boxes = M.list()
    for box in boxes[1]:
        if '"." ' in box:
            dross, folder = box.split('"." ',1)
            output = folder.replace(" ", "_")
            finaloutput = output.replace("\"", "")
            rv, data = M.select(finaloutput)
            if rv == 'OK':
                print "Processing mailbox: ", finaloutput
                process_mailbox(M,finaloutput)
                M.close()
        else:
            print "ERROR: Unable to open mailbox ", rv
    M.logout()

if __name__ == "__main__":
    main()

Output


  MTeam7 [~] $ python imap-dl
Password:
Processing mailbox:  INBOX
Processing mailbox:  INBOX.spam
Writing message  1
Writing message  2
Writing message  3
Processing mailbox:  INBOX.Archive
Writing message  1
Writing message  2
Writing message  3
Writing message  4
Writing message  5
Writing message  6

  Mteam7 [~] $ ls imap-output
total 8.0K
   0 drwxr-xr-x    7 Mteam7 staff  238 Aug 12 01:17 ./
   0 drwxr-xr-x+  11 Mteam7 staff  374 Aug 12 01:33 ../
   0 drwxr-xr-x  114 Mteam7 staff 3.8K Aug 12 01:17 INBOX.Archive/
   0 drwxr-xr-x    3 Mteam7 staff  102 Aug 12 01:17 INBOX.Sent/
   0 drwxr-xr-x    3 Mteam7 staff  102 Aug 12 01:17 INBOX.Trash/
   0 drwxr-xr-x    5 Mteam7 staff  170 Aug 12 01:15 INBOX.spam/
{{ message }}

{{ 'Comments are closed.' | trans }}