Created
June 17, 2025 12:43
-
-
Save sabrysuleiman/8cbd19e823c4e2fe9fe5e9cff25b90e3 to your computer and use it in GitHub Desktop.
Convert maildirs (including subfolders) to mbox format ( python3 )
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
| #!/usr/bin/env python | |
| # | |
| # Convert a maildir to a mbox file. ( python3 ) | |
| # | |
| # Inspired by : Felipe Pena <[email protected]> | |
| # | |
| import mailbox | |
| import sys | |
| import os | |
| from email.parser import BytesParser | |
| def my_factory(fp): | |
| """ | |
| Custom factory to parse email files as bytes. | |
| """ | |
| return BytesParser().parse(fp) | |
| def maildir2mailbox(dirname, mboxname): | |
| """ | |
| Converts a maildir to a mbox file. | |
| """ | |
| # Check if the maildir exists | |
| if not os.path.isdir(dirname): | |
| print("Maildir not found!") | |
| return 1 | |
| mbox = None # Define mbox here to ensure it exists for the finally block | |
| try: | |
| mbox = mailbox.mbox(mboxname, create=True) | |
| mbox.lock() | |
| maildir = mailbox.Maildir(dirname, factory=my_factory, create=False) | |
| for msg in maildir: | |
| mbox.add(msg) | |
| # <--- MODIFICATION: The finally block is updated below --- > | |
| finally: | |
| if mbox is not None: | |
| try: | |
| mbox.flush() | |
| mbox.close() | |
| except Exception as e: | |
| print(f"An error occurred during cleanup: {e}") | |
| return 0 | |
| if __name__ == '__main__': | |
| if len(sys.argv) != 3: | |
| print("Usage: %s <maildir> <mbox>" % sys.argv[0]) | |
| sys.exit(1) | |
| dirname = sys.argv[1] | |
| mboxname = sys.argv[2] | |
| print("%s -> %s" % (dirname, mboxname)) | |
| ret = maildir2mailbox(dirname, mboxname) | |
| sys.exit(ret) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment