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
  • 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 = '[email protected]'
DO_EMAIL_FOLDER = 'INBOX.FolderToBeDownloaded'
# Upload config
UP_IMAP_SERVER = 'imap.example.com'
UP_EMAIL_ACCOUNT = '[email protected]'
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()
@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