Created
September 18, 2016 17:46
-
-
Save grahampugh/c5bbf3e8ec1641ce033791615eee25b0 to your computer and use it in GitHub Desktop.
Archive IMAP E-Mail to local computer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# | |
# Based on https://gist.github.com/robulouski/7442321 | |
# Extended using code from https://ubuntuforums.org/showthread.php?t=993184 | |
# | |
# A Python script to dump all emails from each IMAP folder in an account | |
# to files. | |
# | |
# Mail from each IMAP folder is outputted into a sub-folder of the same name. | |
# | |
# NOTE: running this script will replace any existing files of the same name | |
# in the subfolders. Use at your own risk. | |
# | |
# This code is released into the public domain. | |
# | |
# RKI Nov 2013, extended by GP 2016 | |
# | |
import sys, os | |
import imaplib | |
import getpass | |
# Input your IMAP account settings here: | |
IMAP_SERVER = 'imap.server.com' | |
EMAIL_ACCOUNT = "my.name@server.com" | |
OUTPUT_DIRECTORY = '/Users/myname/email-output' | |
# Don't change anything below here | |
PASSWORD = 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' %(OUTPUT_DIRECTORY, finaloutput) | |
if not os.path.exists(directory): | |
os.makedirs(directory) | |
f = open('%s/%s/%s.eml' %(OUTPUT_DIRECTORY, finaloutput, num), 'wb') | |
f.write(data[0][1]) | |
f.close() | |
def main(): | |
M = imaplib.IMAP4_SSL(IMAP_SERVER) | |
M.login(EMAIL_ACCOUNT, PASSWORD) | |
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment