Metadata-Version: 2.4
Name: emlectomy
Version: 0.1.1
Summary: Surgical removal of the redundancy in an email chain: a clean thread.json + thread.html + attachments from .eml/.msg/.emlx/.mbox
Author: Agustín Rojas
License-Expression: MIT
Project-URL: Homepage, https://github.com/agustinrojas1/emlectomy
Project-URL: Issues, https://github.com/agustinrojas1/emlectomy/issues
Keywords: email,eml,msg,emlx,mbox,deduplication,email-thread,llm,ai-agents
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Communications :: Email
Classifier: Topic :: Text Processing
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# emlectomy

**Surgical removal of the redundancy in an email chain.**

[![tests](https://github.com/agustinrojas1/emlectomy/actions/workflows/tests.yml/badge.svg)](https://github.com/agustinrojas1/emlectomy/actions/workflows/tests.yml)
[![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
![python 3.9+](https://img.shields.io/badge/python-3.9%2B-blue.svg)
![dependencies: none](https://img.shields.io/badge/dependencies-none-brightgreen.svg)

Long reply-all chains repeat themselves. Every message quotes every earlier one, forwards
stack up, signatures and legal disclaimers pile on, and the same PDF gets attached five
times. That is painful to read and expensive to feed to an LLM.

`emlectomy` reads the mess and writes **one folder** with the conversation told once, in
order, containing only what each person actually added.

## Before and after

This is one real-world-shaped email (`examples/gmail-chain.eml`): Alice's third message, which
quotes Bob's reply, which quotes Alice's original, plus her signature and an attachment.

<details open>
<summary><b>Before</b>: what you have to read</summary>

```
From: Alice Johnson <alice@example.com>
To: Bob Smith <bob@example.com>, Carol Diaz <carol@example.com>
Subject: Re: Q3 budget
Date: Wed, 05 Mar 2025 08:30:00 -0500
Attachment: budget-v2.pdf

Done - revised numbers attached. Travel is now 30% lower.

-- 
Alice Johnson
Finance Lead
+1 555 010 2030
www.example.com

On Tue, Mar 4, 2025 at 9:15 AM Bob Smith <bob@example.com> wrote:
> Looks mostly fine to me. The travel line is too high though, we spent half of that last year and nothing has changed.
>
> Bob
>
> On Mon, Mar 3, 2025 at 4:00 PM Alice Johnson <alice@example.com> wrote:
>> Hi team,
>>
>> The Q3 budget draft is attached. Please review the marketing line items before Friday and tell me if anything looks off.
>>
>> Thanks,
>> Alice
```

</details>

```
$ emlectomy examples/gmail-chain.eml
emlectomy: 1 email(s) -> 3 message(s) (0 redundant copies removed, 1 signatures stripped)
  attachments: 1 saved (0 duplicates skipped)
  wrote emlectomy-out/gmail-chain/  (thread.json, thread.html, attachments/)
```

**After**: `thread.html` for humans (attachments are links, never embedded):

<p align="center"><img src="https://raw.githubusercontent.com/agustinrojas1/emlectomy/main/docs/screenshot.png" alt="thread.html: the quoted chain became three separate messages in chronological order" width="560"></p>

and `thread.json` for agents (messages 2 and 3 of 3 shown, the signature moved to `participants`):

```json
[
  {
    "id": 2,
    "from": "Bob Smith <bob@example.com>",
    "to": [],
    "date": "2025-03-04T09:15:00",
    "text": "Looks mostly fine to me. The travel line is too high though, we spent half of that last year and nothing has changed.\n\nBob",
    "attachments": [],
    "source": "quoted_only"
  },
  {
    "id": 3,
    "from": "Alice Johnson <alice@example.com>",
    "to": ["Bob Smith <bob@example.com>", "Carol Diaz <carol@example.com>"],
    "date": "2025-03-05T08:30:00-05:00",
    "text": "Done - revised numbers attached. Travel is now 30% lower.",
    "attachments": [
      {"name": "budget-v2.pdf", "path": "attachments/budget-v2.pdf", "mime": "application/pdf", "size": 45}
    ],
    "source": "email"
  }
]
```

The folder layout:

```
emlectomy-out/gmail-chain/
├── thread.json      for agents: chronological messages, only each one's new text
├── thread.html      for humans: the same clean thread
└── attachments/     every attached file, safe names, identical files stored once
```

- **One file, zero dependencies.** Python 3.9+ standard library only. Copy `emlectomy.py` and run it.
- **Linux, macOS, Windows.** CI runs the tests on all three.
- **Reads** `.eml`, `.msg` (Outlook), `.emlx` (Apple Mail), `.mbox`, folders of them, or stdin.
- **Agent-friendly JSON.** Flat, chronological, stable field names, attachment paths that resolve.

## Quick start

```bash
pipx install emlectomy        # or: pip install emlectomy
emlectomy reply.eml --open
```

No install needed either: grab [`emlectomy.py`](emlectomy.py) and run `python emlectomy.py reply.eml`.
Try it on the samples in this repo:

```bash
git clone https://github.com/agustinrojas1/emlectomy
cd emlectomy
python emlectomy.py examples/budget-thread.mbox --open
```

```
emlectomy FILE [FILE ...] [-o DIR] [--open] [--print-json] [--keep-signatures]
```

| Option | |
|---|---|
| `FILE` | Mail files or folders. `-` reads one from stdin. Several files are merged into one thread. |
| `-o DIR` | Output folder. Default: `emlectomy-out/<file name>`. Re-running overwrites the previous output, and it refuses to write into a non-empty folder that isn't an earlier emlectomy output. |
| `--open` | Open `thread.html` when done. |
| `--print-json` | Also print `thread.json` to stdout (status goes to stderr). Handy for piping to an agent. |
| `--keep-signatures` | Don't strip signatures and disclaimers. |

## What it does

**Peels quoted history into separate messages.** `>` quotes at any depth, `On … wrote:`
attributions (English, Spanish, French, German, Italian, Portuguese, Dutch), Outlook
`-----Original Message-----` and `From: / Sent: / To: / Subject:` blocks, forwarded-message
blocks, and HTML replies (`blockquote`, Outlook's header block). Each older message gets its
sender and date from the attribution or header block.

**Drops redundant copies.** A quoted message is removed when it is already in the thread,
matched on normalised text (ignoring re-wrapping, `>` marks and whitespace), near-duplicate
overlap and paragraph coverage, with sender and date as a sanity check. Two real emails are
only merged when they share a `Message-ID`, or have the same text, sender and timestamp, so
two different "Thanks!" replies stay separate.

**Strips boilerplate.** Signatures (`-- ` delimiter, or sign-off plus contact block), "Sent
from my iPhone", confidentiality disclaimers, `[cid:…]` placeholders, "external email"
banners, Outlook SafeLinks wrappers. Each person's signature is kept once under `participants`.

**Deduplicates attachments.** Identical files (SHA-256) are saved and listed once. Inline
images (e.g. Gmail screenshots) are attached to the message that shows them, and the text
points at the file: `[image: attachments/image (6).png]`.

**Handles inline replies.** When someone answers between quoted lines, the first quote level
stays next to the answers so they still make sense, and anything quoted deeper is peeled off
into its own older messages.

Emails attached to other emails (an `.eml` forwarded as an attachment, or embedded in a
`.msg`) are read as messages and merged into the thread rather than listed as files.

## `thread.json`

```json
{
  "thread": "Q3 budget",
  "base_dir": "/abs/path/emlectomy-out/reply",
  "stats": {
    "emails_read": 3, "message_blocks_seen": 6, "messages_kept": 3,
    "redundant_copies_removed": 3, "signatures_removed": 0,
    "attachments_saved": 1, "duplicate_attachments_skipped": 2
  },
  "participants": [
    {"name": "Alice Johnson", "email": "alice@example.com", "signature": "…"}
  ],
  "messages": [
    {
      "id": 3,
      "from": "Alice Johnson <alice@example.com>",
      "to": ["Bob Smith <bob@example.com>"],
      "date": "2025-03-04T18:00:00+00:00",
      "text": "Agreed with Bob on travel. I will cut it by 30 percent…",
      "attachments": [
        {"name": "budget.pdf", "path": "attachments/budget.pdf",
         "mime": "application/pdf", "size": 45}
      ],
      "source": "email"
    }
  ]
}
```

- Messages are oldest first; `id` is the position.
- Attachment `path`s are relative to the output folder; `base_dir` is its absolute path.
- `cc` and `subject` appear only when present, and `subject` only when it differs from `thread`.
- `source` is `email` (a file you gave it), `attached_email`, or `quoted_only` (the original
  wasn't provided, so the message was rebuilt from a quote and its headers may be partial).
- `date` is `null` with a `date_text` when the date couldn't be parsed.
- `note` appears only on inline-reply messages.

## Limits

- **Heuristics, not magic.** Unusual mail clients or heavily edited quotes can leave a bit of
  repeated text or split a message in the wrong place. `stats` tells you what was removed.
- **A single `.eml` only contains what it quotes.** Replies on other branches of a
  conversation aren't in it. Give emlectomy more files (or an `.mbox`) to cover more.
- **Formatting is plain text.** Colours and highlights (for example answers typed in yellow)
  are lost.
- **`.msg`**: bodies come from the plain-text or HTML property; RTF-only messages aren't decoded.
- **`.pst` / `.ost`** archives aren't supported. Export to `.mbox` or `.eml` first.

## Development

```bash
python -m unittest discover -s tests   # run the tests
python tests/fixtures.py               # regenerate examples/
```

The `.msg` tests use a small OLE writer in `tests/fixtures.py` rather than real Outlook files,
so real-world `.msg` bug reports (with a sample, if you can share one) are especially welcome.
Issues and pull requests are welcome.

## License

[MIT](LICENSE)
