Created
January 24, 2024 10:06
-
-
Save markushuber/1a8cc1edf8353e5471eb7c51ea453536 to your computer and use it in GitHub Desktop.
Simple Python 3 script to convert eml Email files to mbox files.
This file contains hidden or 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
| """ | |
| Simple Python 3 script to convert eml Email files to mbox files. | |
| Convert script requires only The Python Standard Libraries. | |
| This script is useful to convert eml files exported from | |
| E-Mail Accounts to mbox files. Mbox files can be imported | |
| in common email clients such as Outlook, Thunderbird, or | |
| Gnome Evolution. | |
| Placing eml files to be converted to mbox files: | |
| * place all your eml files into the "in" directory: | |
| e.g. in/username_at_email_domain/inbox/123456.eml | |
| Output (mbox-out): | |
| * mbox file for each of the discovered subdirectories with eml files. | |
| """ | |
| import re | |
| import os | |
| import mailbox | |
| from email import policy | |
| from email.parser import BytesParser | |
| eml_regex = re.compile('.*\\.eml') | |
| for directory in ['in', 'mbox-out']: | |
| if not os.path.exists(directory): | |
| os.makedirs(directory) | |
| for root, dirs, files in os.walk("in", topdown=True): | |
| eml_files = list(filter(eml_regex.match, files)) | |
| if eml_files: | |
| output_mbox_file = f'mbox-out/{root.strip("./").replace("/", "-")}.mbox' | |
| if os.path.exists(output_mbox_file): | |
| print(f"WARN: Deleting existing mbox: {output_mbox_file}") | |
| os.remove(output_mbox_file) | |
| print(f'Creating {output_mbox_file} from {len(eml_files)} eml files ...\n') | |
| destination = mailbox.mbox(output_mbox_file) | |
| destination.lock() | |
| for eml_file in eml_files: | |
| eml_file_path = os.path.join(root, eml_file) | |
| with open(eml_file_path, 'rb') as f: | |
| msg = BytesParser(policy=policy.default).parse(f) | |
| destination.add(mailbox.MHMessage(msg)) | |
| destination.flush() | |
| destination.unlock() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment