diff --git a/.gitignore b/.gitignore
index ddf1fd7..86f2abf 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,5 @@
.agentbridge
.idea
+*.egg-info
+build
+dist
\ No newline at end of file
diff --git a/LICENSE-APACHE b/LICENSE-APACHE
new file mode 100644
index 0000000..a7e77cb
--- /dev/null
+++ b/LICENSE-APACHE
@@ -0,0 +1,176 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
\ No newline at end of file
diff --git a/LICENSE-MIT b/LICENSE-MIT
new file mode 100644
index 0000000..eb49541
--- /dev/null
+++ b/LICENSE-MIT
@@ -0,0 +1,19 @@
+Copyright (c) 2025 Wim Pomp-Pervova
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
\ No newline at end of file
diff --git a/README.md b/README.md
index 1808eb1..52a73ed 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,70 @@
# olm2eml
+Convert emails extracted from an Outlook for Mac OLM file into standard `.eml` files. This code is written by OpenCode Zen/Big Pickle.
+
+## Installation
+
+```bash
+git clone https://git.wimpomp.nl/wim/olm2eml.git
+cd olm2eml
+pip install .
+```
+
+## Usage
+
+Point the tool at the directory containing the OLM-extracted XML files:
+
+```bash
+olm2eml /path/to/olm_extracted_emails /path/to/output
+```
+
+Use `--preserve-structure` to mirror the account/folder hierarchy in the output:
+
+```bash
+olm2eml /path/to/olm_extracted_emails /path/to/output --preserve-structure
+```
+
+Use `--overwrite` to replace existing `.eml` files:
+
+```bash
+olm2eml /path/to/olm_extracted_emails /path/to/output --overwrite
+```
+
+You can also run the module directly without installing:
+
+```bash
+python olm_xml_to_eml.py /path/to/olm_extracted_emails /path/to/output
+```
+
+## Input format
+
+The tool expects the directory structure produced by OLM extraction tools (e.g. `olm-export`):
+
+```
+emails_root/
+├── Accounts/
+│ └── account@example.com/
+│ └── com.microsoft.__Messages/
+│ ├── Inbox/
+│ │ ├── message_00000.xml
+│ │ ├── message_00001.xml
+│ │ └── ...
+│ └── Sent Items/
+│ └── ...
+├── Local/
+│ └── ...
+└── Categories.xml
+```
+
+Each `message_*.xml` file contains the email metadata and body. Attachments are stored in sibling
+`com.microsoft.__Attachments/` folders and are referenced by the XML.
+
+## Output
+
+Standard `.eml` files (RFC 2822) compatible with any email client (Thunderbird, Outlook, Apple Mail, etc.). Each email
+preserves:
+
+- Subject, From, To, CC
+- Date, Message-ID, References, In-Reply-To
+- HTML body with plain text fallback
+- Attachments and inline images
diff --git a/olm_xml_to_eml.py b/olm_xml_to_eml.py
new file mode 100644
index 0000000..dcd57ee
--- /dev/null
+++ b/olm_xml_to_eml.py
@@ -0,0 +1,297 @@
+#!/usr/bin/env python3
+"""
+Convert emails extracted from an OLM file (as XML) to standard .eml format.
+
+Usage:
+ python olm_xml_to_eml.py /path/to/emails/root /path/to/output_dir
+"""
+
+import argparse
+import re
+import sys
+import xml.etree.ElementTree as ET
+from email import encoders
+from email.mime.base import MIMEBase
+from email.mime.image import MIMEImage
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+from email.utils import formataddr, formatdate
+from pathlib import Path
+
+EMAILS_ROOT_ATTR = '{http://www.w3.org/XML/1998/namespace}space'
+ADDR_ADDRESS = 'OPFContactEmailAddressAddress'
+ADDR_NAME = 'OPFContactEmailAddressName'
+ADDR_TYPE = 'OPFContactEmailAddressType'
+
+ATTACH_EXT = 'OPFAttachmentContentExtension'
+ATTACH_SIZE = 'OPFAttachmentContentFileSize'
+ATTACH_CID = 'OPFAttachmentContentID'
+ATTACH_TYPE = 'OPFAttachmentContentType'
+ATTACH_NAME = 'OPFAttachmentName'
+ATTACH_URL = 'OPFAttachmentURL'
+
+
+def parse_addresses(parent_elem):
+ addresses = []
+ if parent_elem is None:
+ return addresses
+ for child in parent_elem:
+ if child.tag == 'emailAddress':
+ addr = child.get(ADDR_ADDRESS, '')
+ name = child.get(ADDR_NAME, '')
+ addresses.append((name, addr))
+ return addresses
+
+
+def format_address_list(addresses):
+ parts = []
+ for name, addr in addresses:
+ if name and addr:
+ parts.append(formataddr((name, addr)))
+ elif addr:
+ parts.append(addr)
+ return ', '.join(parts) if parts else ''
+
+
+def parse_attachment_list(parent_elem):
+ attachments = []
+ if parent_elem is None:
+ return attachments
+ for child in parent_elem:
+ if child.tag == 'messageAttachment':
+ att = {
+ 'name': child.get(ATTACH_NAME, 'attachment'),
+ 'content_type': child.get(ATTACH_TYPE, 'application/octet-stream'),
+ 'extension': child.get(ATTACH_EXT, ''),
+ 'content_id': child.get(ATTACH_CID, ''),
+ 'url': child.get(ATTACH_URL, ''),
+ 'size': child.get(ATTACH_SIZE, '0'),
+ }
+ attachments.append(att)
+ return attachments
+
+
+def find_email_xmls(root_dir):
+ xml_files = []
+ root_path = Path(root_dir)
+ for path in root_path.rglob('message_*.xml'):
+ xml_files.append(path)
+ return sorted(xml_files)
+
+
+def get_email_element(xml_path):
+ tree = ET.parse(str(xml_path))
+ root = tree.getroot()
+ return root[0]
+
+
+def text_of(elem):
+ if elem is None:
+ return ''
+ return (elem.text or '').strip()
+
+
+def convert_email_xml_to_eml(xml_path, emails_root):
+ email = get_email_element(xml_path)
+
+ subject = text_of(email.find('OPFMessageCopySubject'))
+
+ from_addrs = parse_addresses(email.find('OPFMessageCopyFromAddresses'))
+ to_addrs = parse_addresses(email.find('OPFMessageCopyToAddresses'))
+ cc_addrs = parse_addresses(email.find('OPFMessageCopyCCAddresses'))
+ reply_to_addrs = parse_addresses(email.find('OPFMessageCopyReplyToAddresses'))
+
+ sender_addr = text_of(email.find('OPFMessageCopySenderAddress'))
+ display_to = text_of(email.find('OPFMessageCopyDisplayTo'))
+
+ sent_time = text_of(email.find('OPFMessageCopySentTime'))
+ received_time = text_of(email.find('OPFMessageCopyReceivedTime'))
+ mod_time = text_of(email.find('OPFMessageCopyModDate'))
+ server_time = text_of(email.find('ExchangeServerLastModifiedTime'))
+
+ message_id = text_of(email.find('OPFMessageCopyMessageID'))
+ in_reply_to = text_of(email.find('OPFMessageCopyInReplyTo'))
+ references = text_of(email.find('OPFMessageCopyReferences'))
+ thread_topic = text_of(email.find('OPFMessageCopyThreadTopic'))
+ conversation_id = text_of(email.find('OPFMessageCopyExchangeConversationId'))
+
+ html_body = text_of(email.find('OPFMessageCopyHTMLBody'))
+ body = text_of(email.find('OPFMessageCopyBody'))
+
+ attachments = parse_attachment_list(email.find('OPFMessageCopyAttachmentList'))
+
+ mime_msg = MIMEMultipart('mixed')
+
+ mime_msg['Subject'] = subject
+
+ from_str = format_address_list(from_addrs)
+ if from_str:
+ mime_msg['From'] = from_str
+ elif sender_addr:
+ mime_msg['From'] = sender_addr
+ else:
+ mime_msg['From'] = 'unknown@unknown.com'
+
+ if from_addrs and display_to:
+ mime_msg['To'] = display_to
+ else:
+ to_str = format_address_list(to_addrs)
+ if to_str:
+ mime_msg['To'] = to_str
+ else:
+ mime_msg['To'] = 'undisclosed-recipients:;'
+
+ cc_str = format_address_list(cc_addrs)
+ if cc_str:
+ mime_msg['Cc'] = cc_str
+
+ reply_to_str = format_address_list(reply_to_addrs)
+ if reply_to_str:
+ mime_msg['Reply-To'] = reply_to_str
+
+ date_str = sent_time or received_time or mod_time or server_time
+ if date_str:
+ mime_msg['Date'] = date_str
+ else:
+ mime_msg['Date'] = formatdate(localtime=True)
+
+ if message_id:
+ mime_msg['Message-ID'] = message_id
+
+ if in_reply_to:
+ mime_msg['In-Reply-To'] = in_reply_to
+
+ if references:
+ mime_msg['References'] = references
+
+ if thread_topic:
+ mime_msg['Thread-Topic'] = thread_topic
+
+ if conversation_id:
+ mime_msg['Thread-Index'] = conversation_id
+
+ mime_msg['MIME-Version'] = '1.0'
+
+ has_html = bool(html_body)
+ has_text = bool(body)
+
+ if has_html or has_text:
+ plain_text = strip_html(body) if body else ''
+ if has_html:
+ body_part = MIMEMultipart('alternative')
+ if plain_text:
+ body_part.attach(MIMEText(plain_text, 'plain', 'utf-8'))
+ body_part.attach(MIMEText(html_body, 'html', 'utf-8'))
+ mime_msg.attach(body_part)
+ elif plain_text:
+ mime_msg.attach(MIMEText(plain_text, 'plain', 'utf-8'))
+ else:
+ mime_msg.attach(MIMEText('', 'plain', 'utf-8'))
+ else:
+ mime_msg.attach(MIMEText('', 'plain', 'utf-8'))
+
+ for att in attachments:
+ att_url = att['url']
+ if not att_url:
+ continue
+ att_path = Path(emails_root) / att_url
+ if not att_path.exists():
+ continue
+ try:
+ data = att_path.read_bytes()
+ content_type = att['content_type'] or 'application/octet-stream'
+ if '/' in content_type:
+ main_type, sub_type = content_type.split('/', 1)
+ else:
+ main_type, sub_type = 'application', 'octet-stream'
+
+ if main_type == 'image':
+ part = MIMEImage(data, _subtype=sub_type)
+ else:
+ part = MIMEBase(main_type, sub_type)
+ part.set_payload(data)
+ encoders.encode_base64(part)
+
+ filename = att['name']
+ cid = att['content_id']
+ if cid:
+ part.add_header('Content-ID', f'<{cid}>')
+ part.add_header('Content-Disposition', 'inline', filename=filename)
+ else:
+ part.add_header('Content-Disposition', 'attachment', filename=filename)
+
+ mime_msg.attach(part)
+ except Exception as e:
+ print(f" Warning: failed to attach {att_url}: {e}", file=sys.stderr)
+
+ return mime_msg.as_bytes()
+
+
+def strip_html(html_text):
+ text = re.sub(r'', '', html_text, flags=re.DOTALL)
+ text = re.sub(r'', '', text, flags=re.DOTALL)
+ text = re.sub(r'<[^>]+>', ' ', text)
+ text = re.sub(r'\s+', ' ', text)
+ return text.strip()
+
+
+def build_output_path(xml_path, emails_root, output_dir, preserve_structure):
+ if preserve_structure:
+ rel = xml_path.parent.relative_to(Path(emails_root).resolve())
+ out = Path(output_dir) / rel / f"{xml_path.stem}.eml"
+ else:
+ out = Path(output_dir) / f"{xml_path.stem}.eml"
+ out.parent.mkdir(parents=True, exist_ok=True)
+ return out
+
+
+def main():
+ parser = argparse.ArgumentParser(description='Convert OLM-extracted XML emails to EML format')
+ parser.add_argument('input_dir', help='Root directory of the extracted OLM emails')
+ parser.add_argument('output_dir', help='Output directory for EML files')
+ parser.add_argument('--preserve-structure', action='store_true',
+ help='Preserve folder structure in output (mirrors account/folder hierarchy)')
+ parser.add_argument('--overwrite', action='store_true', help='Overwrite existing EML files')
+
+ args = parser.parse_args()
+
+ input_dir = Path(args.input_dir).resolve()
+ output_dir = Path(args.output_dir).resolve()
+
+ if not input_dir.is_dir():
+ print(f"Error: input directory not found: {input_dir}", file=sys.stderr)
+ sys.exit(1)
+
+ output_dir.mkdir(parents=True, exist_ok=True)
+
+ xml_files = find_email_xmls(input_dir)
+ if not xml_files:
+ print(f"No message_*.xml files found in {input_dir}", file=sys.stderr)
+ sys.exit(1)
+
+ print(f"Found {len(xml_files)} email XML files")
+
+ success = 0
+ skipped = 0
+ errors = 0
+
+ for xml_path in xml_files:
+ out_path = build_output_path(xml_path, input_dir, output_dir, args.preserve_structure)
+
+ if out_path.exists() and not args.overwrite:
+ skipped += 1
+ continue
+
+ try:
+ eml_bytes = convert_email_xml_to_eml(xml_path, input_dir)
+ out_path.write_bytes(eml_bytes)
+ success += 1
+ except Exception as e:
+ print(f"Error converting {xml_path}: {e}", file=sys.stderr)
+ errors += 1
+
+ print(f"\nDone. {success} converted, {skipped} skipped, {errors} errors.")
+
+
+if __name__ == '__main__':
+ main()
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..46711bf
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,29 @@
+[build-system]
+requires = ["setuptools"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "olm2eml"
+version = "0.1.0"
+description = "Convert OLM-extracted email XML files to standard EML format"
+readme = "README.md"
+requires-python = ">=3.8"
+classifiers = [
+ "License :: OSI Approved :: Apache Software License",
+ "License :: OSI Approved :: MIT License",
+ "Programming Language :: Python",
+ "Programming Language :: Python :: 3",
+]
+authors = [
+ { name = "Wim Pomp-Pervova" },
+]
+license = { text = "MIT OR Apache-2.0" }
+
+[project.urls]
+repository = "https://git.wimpomp.nl/wim/olm2eml"
+
+[project.scripts]
+olm2eml = "olm_xml_to_eml:main"
+
+[tool.setuptools]
+py-modules = ["olm_xml_to_eml"]