Metadata-Version: 2.4
Name: mailreader
Version: 2.7.1
Summary: Sanitized HTML mail parsing built on the confext HTML parser
Author-email: nigarash <nigarash@gmail.com>
License: MIT
Keywords: mail,email,htmlparser,sanitize,mime
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Communications :: Email
Classifier: Topic :: Text Processing :: Markup :: HTML
Classifier: Typing :: Typed
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: confext
Dynamic: license-file

mailreader is a mail parser, nothing else: all generic HTML machinery
(selectors, sanitization) lives inside the package as internal
machinery. It is a library only: there is no command-line interface.

## Installation

```powershell
pip install mailreader
```

## Quick start

```python
import mailreader

raw = b'''From: Alice <alice@example.com>
To: bob@example.org
Subject: =?utf-8?q?Quarterly_report_=E2=9C=93?=
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="BOUND"

--BOUND
Content-Type: text/plain; charset="utf-8"

Hi Bob, the numbers are fine.

> On Monday you wrote:
> numbers look off
I double-checked.

--
Alice

--BOUND
Content-Type: text/html; charset="utf-8"

<html><body>
<script>alert('xss')</script>
<p>Hi Bob, the numbers are <b>fine</b>.</p>
<img src="https://tracker.example/pixel.gif" onerror="steal()">
<a href="https://example.com/report">details</a>
<img src="cid:chart.png">
</body></html>
--BOUND--
'''

doc = mailreader.parse_mail(raw)
doc.subject            # 'Quarterly report ✓' (encoded-word decoded)
doc.from_              # 'Alice <alice@example.com>'
doc.text               # readable text: quoted reply + signature stripped
doc.attachments        # [] here; see MailDocument below
mailreader.mail_to_html(raw)
# '<div><div> <div>Quarterly report</div> <p>Hi Bob, the numbers are <b>fine</b>.</p> ...'
# script, onerror, and the remote pixel are gone; non-whitelisted tags
# (h1, img) collapse to div, remote hrefs are stripped, and the cid:
# src survives for inline images
mailreader.select_mail(raw, 'a')   # [{'tag': 'a', 'attrs': ..., 'text': ..., 'html': ...}]
mailreader.readable_text(raw)      # same as doc.text
```

## API

### Mail parsing

| Function | Description |
|---|---|
| `parse_mail(raw, include_payload=False)` | Parse a raw message (`str`/`bytes`) into a `MailDocument`. Walks multipart/alternative preferring `text/html` (with a `text/plain` → minimal-HTML fallback; a message with neither text part yields a constant empty body), decodes charsets (part charset → config `encoding` fallback), then parses and sanitizes via the active engine. `include_payload=True` adds raw `payload` bytes to attachment entries. |
| `readable_text(raw)` | Readable plain text of a mail: quoted reply lines (`> …`) and everything after a `-- `/`--` signature marker stripped, blank runs collapsed. |
| `select_mail(raw, selector)` | CSS selector over the sanitized mail HTML; returns dicts per match. |
| `mail_to_html(raw)` | The sanitized mail HTML as a string. |

### MailDocument

`parse_mail` returns a `MailDocument` with:

| Field | Description |
|---|---|
| `headers` | Dict of decoded headers (repeated headers joined with `", "`). |
| `subject`, `from_` | Header convenience properties (`''` when missing). |
| `html` | The sanitized body as a confext `ParsedDocument` (or `None`). |
| `text` | Readable plain text (from the `text/plain` part when present, else extracted from the sanitized HTML). |
| `parts` | Every leaf part as `{'content_type', 'charset', 'disposition', 'filename', 'content_id', 'size'}`. |
| `attachments` | Same shape, restricted to attachments (a filename or an attachment disposition); plus `payload` bytes when `include_payload=True`. |
| `inline_images` | Remaining image parts carrying a `Content-ID`. |
| `config` | Snapshot of the engine config used. |
| `to_dict()` | All of the above as a plain dict (additionally reports document `stats`). |

### Sanitization

Mail HTML is always sanitized before it is exposed, via
`MailReaderEngine.sanitize` with policy keys falling back to config
entries. The policy:

| Key | Default | Behavior |
|---|---|---|
| `remove_scripts` | `True` | Drop `<script>`, `<style>`, `<iframe>`, `<object>`, `<embed>`, `<applet>` nodes. |
| `remove_event_handlers` | `True` | Drop every `on*` attribute. |
| `remove_remote_content` | `True` | Drop media nodes (`img`, `source`, …) with remote `src`; drop remote `http(s)`/`//` URL attributes elsewhere. `javascript:` URLs are always dropped. `cid:` references are kept for inline images. |
| `allowed_tags` | `None` | Optional tag whitelist; tags outside it are replaced by `default_tag` or removed. |
| `default_tag` | `None` | Replacement tag for non-whitelisted elements. |

A malformed policy (non-dict policy, non-boolean flags, a bare string
as `allowed_tags`, a non-string `default_tag`) raises
`SanitizationError`.

### Selectors

`select_mail` supports: comma groups (`p, li`), compounds (`tag`,
`#id`, `.class` repeatable, `[attr]`, `[attr=val]` with quoted or
unquoted values), the universal selector (`*`), combinators —
descendant (`div ul li`), child (`div > p`), adjacent sibling
(`li + li`), general sibling (`li ~ li`) — attribute operators (`=`
exact, `^=` prefix, `$=` suffix, `*=` substring, `~=` word, `|=`
prefix-with-dash), and the pseudo-classes `:first-child`,
`:last-child`, and `:nth-child(...)` (`odd`, `even`, `3`, `2n`,
`2n+1`).

Unsupported (raises `SelectorSyntaxError`): other pseudo-classes
(`:root`, `:hover`, …), pseudo-elements (`::before`), and attribute
values containing unquoted spaces.

### Engine wiring

| Function / class | Description |
|---|---|
| `get_config()` | The active config dict; lazily loads `default.config`. If it is missing or unsafe, falls back to the engine's built-in defaults. |
| `get_engine()` | The active `MailReaderEngine` built from that config. |
| `reload(path=None)` | (Re)load a config and rebuild the engine. No path reloads the bundled `default.config`; a path adopts that file. Raises `ConfigLoadError` on bad input. |
| `MailReaderEngine(config=None, use_cache=True)` | A `confext.Engine` subclass: inherits `parse` (with caching, limits, strict mode) and adds `sanitize`, honoring the sanitize config keys. |

#### Auto-discovery rules

With no explicit path, `load_config`/`save_config` inspect their
direct caller's frame (depth 1) and resolve, in order:

1. `default.config` in the directory of the calling module's file.
2. `default.config` at the calling package's root (via `__package__`,
   resolved with `importlib.util.find_spec`), returned even when absent
   so a first save can bootstrap it.

No candidate (REPL, `exec`, `__main__`) → `ConfigLoadError`; pass a
path. `get_config`/`get_engine`/`reload` always resolve to
mailreader's own bundled `default.config`.

## Configuration

The bundled `default.config` (confext format: an 8-byte sha256
checksum, a 4-byte big-endian size, then the pickled settings) holds
the parser keys forwarded to confext plus the sanitize keys:

| Key | Default | Used by |
|---|---|---|
| `encoding` | `'utf-8'` | Fallback charset for mail parts. |
| `max_depth` | `100` | confext parse: element nesting cap. |
| `max_file_size_mb` | `10` | confext parse: input size cap. |
| `cache_size` | `50` | confext parse: LRU capacity. |
| `strict_mode` | `False` | confext parse: raise on malformed HTML. |
| `strip_whitespace` | `True` | confext parse: collapse text whitespace. |
| `preserve_comments` | `False` | confext parse: keep comments in the tree. |
| `allowed_tags` | `['a', 'b', 'br', 'div', 'i', 'li', 'ol', 'p', 'span', 'ul']` | sanitize whitelist. Stored as a list — sets cannot round-trip through `save_config`. |
| `default_tag` | `'div'` | sanitize replacement for non-whitelisted tags. |
| `remove_scripts` | `True` | sanitize: drop script/style/iframe/object/embed nodes. |
| `remove_remote_content` | `True` | sanitize: drop remote images/media and remote URL attributes. |
| `remove_event_handlers` | `True` | sanitize: drop `on*` attributes. |

## Errors

```
MailReaderError
├── ConfigLoadError      config file missing/invalid/unsafe/undiscoverable
├── SanitizationError    malformed sanitize policy
╰── SelectorSyntaxError  invalid or unsupported selector

HTMLParserError (confext)  base error of the underlying parser package
```

All re-exported from the package root (confext's via `import confext`).

## Versioning

mailreader follows [semver](https://semver.org/) `MAJOR.MINOR.PATCH`;
the current version is available as `mailreader.__version__`. Licensed
under the MIT License — see [LICENSE](LICENSE).
