-
-
Save khachuy2705/c5608841b4e7104882800ce47876be4b to your computer and use it in GitHub Desktop.
Very simple Python script to download/upload emails from/to an IMAP folder.
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 | |
# | |
# 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 | |
# khachuy2705 2025: Preserve the timestamp of the email message | |
import os | |
import sys | |
import imaplib | |
import getpass | |
import eml_parser | |
ep = eml_parser.EmlParser() | |
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)}') | |
eml_read = eml.read() | |
try: | |
parsed_eml = ep.decode_email_bytes(eml_read) | |
rv, message = M.append(UP_EMAIL_FOLDER, None, parsed_eml["header"]["date"], 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment