Skip to main content

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

pip install mailreader

Quick start

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 MAJOR.MINOR.PATCH; the current version is available as mailreader.__version__. Licensed under the MIT License — see LICENSE.

Metadata

Release files for mailreader 2.7.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mailreader 2.7.1
File Size Uploaded Provenance Actions
mailreader-2.7.1.tar.gz 24.1 kB Without provenance Details for mailreader-2.7.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mailreader 2.7.1
File Interpreter ABI Platform Actions
mailreader-2.7.1-py3-none-any.whl Python 3 none any Details for mailreader-2.7.1-py3-none-any.whl

Total release size: 44.7 kB

Release files / mailreader-2.7.1.tar.gz

Download URL mailreader-2.7.1.tar.gz
Size 24.1 kB
Tags Source
SHA-256 checksum
How to use checksums
d42001978f2aa2b528b91508771582c53638ede6ef1571efbe4d9a775275a2f3
BLAKE2b-256 checksum
How to use checksums
b240f6938882a30f2c58f75eda6b8f931774c099335ac6adad00125d8761488d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.7

Release files / mailreader-2.7.1-py3-none-any.whl

Download URL mailreader-2.7.1-py3-none-any.whl
Size 20.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
824b3df224c9052ae9c01f4dc6807014eecb37855fc888b16c9098887f962fb0
BLAKE2b-256 checksum
How to use checksums
57ece87fe8dcf8cab74458877a896e62447dfd75e55a9a154fa6cc8bdded1b56
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.7

Security for mailreader 2.7.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.7.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page