Skip to content

Instantly share code, notes, and snippets.

@paloha
Forked from robulouski/gmail_imap_dump_eml.py
Last active August 17, 2023 10:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save paloha/a5dc2843a342b1f8b814c92a098ca2a2 to your computer and use it in GitHub Desktop.
Save paloha/a5dc2843a342b1f8b814c92a098ca2a2 to your computer and use it in GitHub Desktop.
Very simple Python script to download/upload emails from/to an IMAP folder.
#!/usr/bin/env python
#
# Very simple Python script to download/upload emails from/to an IMAP folder.
# This code is based on a simpler version from https://gist.github.com/robulouski/7442321
# This code is released into the public domain.
#
# Paloha 2020
import os
import sys
import imaplib
import getpass
LOCAL_DIRECTORY = 'tmp' # Must be created manually
# Download config
DO_IMAP_SERVER = 'imap.example.com'
DO_EMAIL_ACCOUNT = 'somebody@example.com'
DO_EMAIL_FOLDER = 'INBOX.FolderToBeDownloaded'
# Upload config
UP_IMAP_SERVER = 'imap.example.com'
UP_EMAIL_ACCOUNT = 'elsebody@example.com'
UP_EMAIL_FOLDER = 'INBOX.FolderToUpload'
MODE = ['DOWNLOAD', 'UPLOAD'][int(input('Select mode: 0 for download, 1 for upload: '))]
PASSWORD = getpass.getpass()
def mailbox_login(server, account, password):
M = imaplib.IMAP4_SSL(server)
M.login(account, password)
return M
def main():
print(f'Mode: {MODE}')
if MODE == 'DOWNLOAD':
M = mailbox_login(DO_IMAP_SERVER, DO_EMAIL_ACCOUNT, PASSWORD)
rv, data = M.select(DO_EMAIL_FOLDER)
if rv == 'OK':
print('Downloading from: ', DO_EMAIL_FOLDER)
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', int(num))
return
fname = os.path.join(LOCAL_DIRECTORY, f'{int(num)}.eml')
print(f'Writing message {fname}')
with open(fname, 'wb') as f:
f.write(data[0][1])
M.close()
else:
print('ERROR: Unable to open mailbox ', rv)
M.logout()
if MODE == 'UPLOAD':
# Login and check if folder exists
M = mailbox_login(UP_IMAP_SERVER, UP_EMAIL_ACCOUNT, PASSWORD)
available_folders = list(map(lambda x: x.split()[-1].decode(), M.list()[1]))
assert UP_EMAIL_FOLDER in available_folders, 'IMAP folder not on server.'
print(f'Uploading to: {UP_EMAIL_FOLDER}')
# Open all .eml files in desired dir and upload them to the server
eml_fnames = [f for f in os.listdir(LOCAL_DIRECTORY) if f.endswith('.eml')]
failed_uploads = []
for i, eml_fname in enumerate(eml_fnames):
with open(os.path.join(LOCAL_DIRECTORY, eml_fname), 'rb') as eml:
print(f'Uploading email {eml_fname} | {i+1}/{len(eml_fnames)}')
try:
rv, message = M.append(UP_EMAIL_FOLDER, None, None, eml.read())
except Exception as e:
rv = 'ERR'
message = e
if rv != 'OK':
failed_uploads.append(eml_fname)
print('ERROR uploading message.')
print(message)
print('Upload complete')
print(f'{len(failed_uploads)} failed uploads.')
print(failed_uploads)
M.logout()
if __name__ == '__main__':
main()
@nfl0
Copy link

nfl0 commented Sep 9, 2021

@paloha
Copy link
Author

paloha commented Sep 9, 2021

@nfl0 I am not sure why you have added this comment. But I am quite positive that you did not want to upload your gmail credentials for everyone to see, right? I guess you should remove the comment and the gist for your own protection.

@melidosian
Copy link

@paloha two years later and his credentials have not changed, but he has MFA now 🤣

Anyways - thanks for the script! You helped me back up a Yandex mail account and migrate it to Gmail!

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