mailreader 2.7.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The mailreader developers
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,209 @@
1
+ Metadata-Version: 2.4
2
+ Name: mailreader
3
+ Version: 2.7.1
4
+ Summary: Sanitized HTML mail parsing built on the confext HTML parser
5
+ Author-email: nigarash <nigarash@gmail.com>
6
+ License: MIT
7
+ Keywords: mail,email,htmlparser,sanitize,mime
8
+ Classifier: Development Status :: 5 - Production/Stable
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Communications :: Email
19
+ Classifier: Topic :: Text Processing :: Markup :: HTML
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.8
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: confext
25
+ Dynamic: license-file
26
+
27
+ mailreader is a mail parser, nothing else: all generic HTML machinery
28
+ (selectors, sanitization) lives inside the package as internal
29
+ machinery. It is a library only: there is no command-line interface.
30
+
31
+ ## Installation
32
+
33
+ ```powershell
34
+ pip install mailreader
35
+ ```
36
+
37
+ ## Quick start
38
+
39
+ ```python
40
+ import mailreader
41
+
42
+ raw = b'''From: Alice <alice@example.com>
43
+ To: bob@example.org
44
+ Subject: =?utf-8?q?Quarterly_report_=E2=9C=93?=
45
+ MIME-Version: 1.0
46
+ Content-Type: multipart/alternative; boundary="BOUND"
47
+
48
+ --BOUND
49
+ Content-Type: text/plain; charset="utf-8"
50
+
51
+ Hi Bob, the numbers are fine.
52
+
53
+ > On Monday you wrote:
54
+ > numbers look off
55
+ I double-checked.
56
+
57
+ --
58
+ Alice
59
+
60
+ --BOUND
61
+ Content-Type: text/html; charset="utf-8"
62
+
63
+ <html><body>
64
+ <script>alert('xss')</script>
65
+ <p>Hi Bob, the numbers are <b>fine</b>.</p>
66
+ <img src="https://tracker.example/pixel.gif" onerror="steal()">
67
+ <a href="https://example.com/report">details</a>
68
+ <img src="cid:chart.png">
69
+ </body></html>
70
+ --BOUND--
71
+ '''
72
+
73
+ doc = mailreader.parse_mail(raw)
74
+ doc.subject # 'Quarterly report ✓' (encoded-word decoded)
75
+ doc.from_ # 'Alice <alice@example.com>'
76
+ doc.text # readable text: quoted reply + signature stripped
77
+ doc.attachments # [] here; see MailDocument below
78
+ mailreader.mail_to_html(raw)
79
+ # '<div><div> <div>Quarterly report</div> <p>Hi Bob, the numbers are <b>fine</b>.</p> ...'
80
+ # script, onerror, and the remote pixel are gone; non-whitelisted tags
81
+ # (h1, img) collapse to div, remote hrefs are stripped, and the cid:
82
+ # src survives for inline images
83
+ mailreader.select_mail(raw, 'a') # [{'tag': 'a', 'attrs': ..., 'text': ..., 'html': ...}]
84
+ mailreader.readable_text(raw) # same as doc.text
85
+ ```
86
+
87
+ ## API
88
+
89
+ ### Mail parsing
90
+
91
+ | Function | Description |
92
+ |---|---|
93
+ | `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. |
94
+ | `readable_text(raw)` | Readable plain text of a mail: quoted reply lines (`> …`) and everything after a `-- `/`--` signature marker stripped, blank runs collapsed. |
95
+ | `select_mail(raw, selector)` | CSS selector over the sanitized mail HTML; returns dicts per match. |
96
+ | `mail_to_html(raw)` | The sanitized mail HTML as a string. |
97
+
98
+ ### MailDocument
99
+
100
+ `parse_mail` returns a `MailDocument` with:
101
+
102
+ | Field | Description |
103
+ |---|---|
104
+ | `headers` | Dict of decoded headers (repeated headers joined with `", "`). |
105
+ | `subject`, `from_` | Header convenience properties (`''` when missing). |
106
+ | `html` | The sanitized body as a confext `ParsedDocument` (or `None`). |
107
+ | `text` | Readable plain text (from the `text/plain` part when present, else extracted from the sanitized HTML). |
108
+ | `parts` | Every leaf part as `{'content_type', 'charset', 'disposition', 'filename', 'content_id', 'size'}`. |
109
+ | `attachments` | Same shape, restricted to attachments (a filename or an attachment disposition); plus `payload` bytes when `include_payload=True`. |
110
+ | `inline_images` | Remaining image parts carrying a `Content-ID`. |
111
+ | `config` | Snapshot of the engine config used. |
112
+ | `to_dict()` | All of the above as a plain dict (additionally reports document `stats`). |
113
+
114
+ ### Sanitization
115
+
116
+ Mail HTML is always sanitized before it is exposed, via
117
+ `MailReaderEngine.sanitize` with policy keys falling back to config
118
+ entries. The policy:
119
+
120
+ | Key | Default | Behavior |
121
+ |---|---|---|
122
+ | `remove_scripts` | `True` | Drop `<script>`, `<style>`, `<iframe>`, `<object>`, `<embed>`, `<applet>` nodes. |
123
+ | `remove_event_handlers` | `True` | Drop every `on*` attribute. |
124
+ | `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. |
125
+ | `allowed_tags` | `None` | Optional tag whitelist; tags outside it are replaced by `default_tag` or removed. |
126
+ | `default_tag` | `None` | Replacement tag for non-whitelisted elements. |
127
+
128
+ A malformed policy (non-dict policy, non-boolean flags, a bare string
129
+ as `allowed_tags`, a non-string `default_tag`) raises
130
+ `SanitizationError`.
131
+
132
+ ### Selectors
133
+
134
+ `select_mail` supports: comma groups (`p, li`), compounds (`tag`,
135
+ `#id`, `.class` repeatable, `[attr]`, `[attr=val]` with quoted or
136
+ unquoted values), the universal selector (`*`), combinators —
137
+ descendant (`div ul li`), child (`div > p`), adjacent sibling
138
+ (`li + li`), general sibling (`li ~ li`) — attribute operators (`=`
139
+ exact, `^=` prefix, `$=` suffix, `*=` substring, `~=` word, `|=`
140
+ prefix-with-dash), and the pseudo-classes `:first-child`,
141
+ `:last-child`, and `:nth-child(...)` (`odd`, `even`, `3`, `2n`,
142
+ `2n+1`).
143
+
144
+ Unsupported (raises `SelectorSyntaxError`): other pseudo-classes
145
+ (`:root`, `:hover`, …), pseudo-elements (`::before`), and attribute
146
+ values containing unquoted spaces.
147
+
148
+ ### Engine wiring
149
+
150
+ | Function / class | Description |
151
+ |---|---|
152
+ | `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. |
153
+ | `get_engine()` | The active `MailReaderEngine` built from that config. |
154
+ | `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. |
155
+ | `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. |
156
+
157
+ #### Auto-discovery rules
158
+
159
+ With no explicit path, `load_config`/`save_config` inspect their
160
+ direct caller's frame (depth 1) and resolve, in order:
161
+
162
+ 1. `default.config` in the directory of the calling module's file.
163
+ 2. `default.config` at the calling package's root (via `__package__`,
164
+ resolved with `importlib.util.find_spec`), returned even when absent
165
+ so a first save can bootstrap it.
166
+
167
+ No candidate (REPL, `exec`, `__main__`) → `ConfigLoadError`; pass a
168
+ path. `get_config`/`get_engine`/`reload` always resolve to
169
+ mailreader's own bundled `default.config`.
170
+
171
+ ## Configuration
172
+
173
+ The bundled `default.config` (confext format: an 8-byte sha256
174
+ checksum, a 4-byte big-endian size, then the pickled settings) holds
175
+ the parser keys forwarded to confext plus the sanitize keys:
176
+
177
+ | Key | Default | Used by |
178
+ |---|---|---|
179
+ | `encoding` | `'utf-8'` | Fallback charset for mail parts. |
180
+ | `max_depth` | `100` | confext parse: element nesting cap. |
181
+ | `max_file_size_mb` | `10` | confext parse: input size cap. |
182
+ | `cache_size` | `50` | confext parse: LRU capacity. |
183
+ | `strict_mode` | `False` | confext parse: raise on malformed HTML. |
184
+ | `strip_whitespace` | `True` | confext parse: collapse text whitespace. |
185
+ | `preserve_comments` | `False` | confext parse: keep comments in the tree. |
186
+ | `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`. |
187
+ | `default_tag` | `'div'` | sanitize replacement for non-whitelisted tags. |
188
+ | `remove_scripts` | `True` | sanitize: drop script/style/iframe/object/embed nodes. |
189
+ | `remove_remote_content` | `True` | sanitize: drop remote images/media and remote URL attributes. |
190
+ | `remove_event_handlers` | `True` | sanitize: drop `on*` attributes. |
191
+
192
+ ## Errors
193
+
194
+ ```
195
+ MailReaderError
196
+ ├── ConfigLoadError config file missing/invalid/unsafe/undiscoverable
197
+ ├── SanitizationError malformed sanitize policy
198
+ ╰── SelectorSyntaxError invalid or unsupported selector
199
+
200
+ HTMLParserError (confext) base error of the underlying parser package
201
+ ```
202
+
203
+ All re-exported from the package root (confext's via `import confext`).
204
+
205
+ ## Versioning
206
+
207
+ mailreader follows [semver](https://semver.org/) `MAJOR.MINOR.PATCH`;
208
+ the current version is available as `mailreader.__version__`. Licensed
209
+ under the MIT License — see [LICENSE](LICENSE).
@@ -0,0 +1,183 @@
1
+ mailreader is a mail parser, nothing else: all generic HTML machinery
2
+ (selectors, sanitization) lives inside the package as internal
3
+ machinery. It is a library only: there is no command-line interface.
4
+
5
+ ## Installation
6
+
7
+ ```powershell
8
+ pip install mailreader
9
+ ```
10
+
11
+ ## Quick start
12
+
13
+ ```python
14
+ import mailreader
15
+
16
+ raw = b'''From: Alice <alice@example.com>
17
+ To: bob@example.org
18
+ Subject: =?utf-8?q?Quarterly_report_=E2=9C=93?=
19
+ MIME-Version: 1.0
20
+ Content-Type: multipart/alternative; boundary="BOUND"
21
+
22
+ --BOUND
23
+ Content-Type: text/plain; charset="utf-8"
24
+
25
+ Hi Bob, the numbers are fine.
26
+
27
+ > On Monday you wrote:
28
+ > numbers look off
29
+ I double-checked.
30
+
31
+ --
32
+ Alice
33
+
34
+ --BOUND
35
+ Content-Type: text/html; charset="utf-8"
36
+
37
+ <html><body>
38
+ <script>alert('xss')</script>
39
+ <p>Hi Bob, the numbers are <b>fine</b>.</p>
40
+ <img src="https://tracker.example/pixel.gif" onerror="steal()">
41
+ <a href="https://example.com/report">details</a>
42
+ <img src="cid:chart.png">
43
+ </body></html>
44
+ --BOUND--
45
+ '''
46
+
47
+ doc = mailreader.parse_mail(raw)
48
+ doc.subject # 'Quarterly report ✓' (encoded-word decoded)
49
+ doc.from_ # 'Alice <alice@example.com>'
50
+ doc.text # readable text: quoted reply + signature stripped
51
+ doc.attachments # [] here; see MailDocument below
52
+ mailreader.mail_to_html(raw)
53
+ # '<div><div> <div>Quarterly report</div> <p>Hi Bob, the numbers are <b>fine</b>.</p> ...'
54
+ # script, onerror, and the remote pixel are gone; non-whitelisted tags
55
+ # (h1, img) collapse to div, remote hrefs are stripped, and the cid:
56
+ # src survives for inline images
57
+ mailreader.select_mail(raw, 'a') # [{'tag': 'a', 'attrs': ..., 'text': ..., 'html': ...}]
58
+ mailreader.readable_text(raw) # same as doc.text
59
+ ```
60
+
61
+ ## API
62
+
63
+ ### Mail parsing
64
+
65
+ | Function | Description |
66
+ |---|---|
67
+ | `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. |
68
+ | `readable_text(raw)` | Readable plain text of a mail: quoted reply lines (`> …`) and everything after a `-- `/`--` signature marker stripped, blank runs collapsed. |
69
+ | `select_mail(raw, selector)` | CSS selector over the sanitized mail HTML; returns dicts per match. |
70
+ | `mail_to_html(raw)` | The sanitized mail HTML as a string. |
71
+
72
+ ### MailDocument
73
+
74
+ `parse_mail` returns a `MailDocument` with:
75
+
76
+ | Field | Description |
77
+ |---|---|
78
+ | `headers` | Dict of decoded headers (repeated headers joined with `", "`). |
79
+ | `subject`, `from_` | Header convenience properties (`''` when missing). |
80
+ | `html` | The sanitized body as a confext `ParsedDocument` (or `None`). |
81
+ | `text` | Readable plain text (from the `text/plain` part when present, else extracted from the sanitized HTML). |
82
+ | `parts` | Every leaf part as `{'content_type', 'charset', 'disposition', 'filename', 'content_id', 'size'}`. |
83
+ | `attachments` | Same shape, restricted to attachments (a filename or an attachment disposition); plus `payload` bytes when `include_payload=True`. |
84
+ | `inline_images` | Remaining image parts carrying a `Content-ID`. |
85
+ | `config` | Snapshot of the engine config used. |
86
+ | `to_dict()` | All of the above as a plain dict (additionally reports document `stats`). |
87
+
88
+ ### Sanitization
89
+
90
+ Mail HTML is always sanitized before it is exposed, via
91
+ `MailReaderEngine.sanitize` with policy keys falling back to config
92
+ entries. The policy:
93
+
94
+ | Key | Default | Behavior |
95
+ |---|---|---|
96
+ | `remove_scripts` | `True` | Drop `<script>`, `<style>`, `<iframe>`, `<object>`, `<embed>`, `<applet>` nodes. |
97
+ | `remove_event_handlers` | `True` | Drop every `on*` attribute. |
98
+ | `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. |
99
+ | `allowed_tags` | `None` | Optional tag whitelist; tags outside it are replaced by `default_tag` or removed. |
100
+ | `default_tag` | `None` | Replacement tag for non-whitelisted elements. |
101
+
102
+ A malformed policy (non-dict policy, non-boolean flags, a bare string
103
+ as `allowed_tags`, a non-string `default_tag`) raises
104
+ `SanitizationError`.
105
+
106
+ ### Selectors
107
+
108
+ `select_mail` supports: comma groups (`p, li`), compounds (`tag`,
109
+ `#id`, `.class` repeatable, `[attr]`, `[attr=val]` with quoted or
110
+ unquoted values), the universal selector (`*`), combinators —
111
+ descendant (`div ul li`), child (`div > p`), adjacent sibling
112
+ (`li + li`), general sibling (`li ~ li`) — attribute operators (`=`
113
+ exact, `^=` prefix, `$=` suffix, `*=` substring, `~=` word, `|=`
114
+ prefix-with-dash), and the pseudo-classes `:first-child`,
115
+ `:last-child`, and `:nth-child(...)` (`odd`, `even`, `3`, `2n`,
116
+ `2n+1`).
117
+
118
+ Unsupported (raises `SelectorSyntaxError`): other pseudo-classes
119
+ (`:root`, `:hover`, …), pseudo-elements (`::before`), and attribute
120
+ values containing unquoted spaces.
121
+
122
+ ### Engine wiring
123
+
124
+ | Function / class | Description |
125
+ |---|---|
126
+ | `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. |
127
+ | `get_engine()` | The active `MailReaderEngine` built from that config. |
128
+ | `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. |
129
+ | `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. |
130
+
131
+ #### Auto-discovery rules
132
+
133
+ With no explicit path, `load_config`/`save_config` inspect their
134
+ direct caller's frame (depth 1) and resolve, in order:
135
+
136
+ 1. `default.config` in the directory of the calling module's file.
137
+ 2. `default.config` at the calling package's root (via `__package__`,
138
+ resolved with `importlib.util.find_spec`), returned even when absent
139
+ so a first save can bootstrap it.
140
+
141
+ No candidate (REPL, `exec`, `__main__`) → `ConfigLoadError`; pass a
142
+ path. `get_config`/`get_engine`/`reload` always resolve to
143
+ mailreader's own bundled `default.config`.
144
+
145
+ ## Configuration
146
+
147
+ The bundled `default.config` (confext format: an 8-byte sha256
148
+ checksum, a 4-byte big-endian size, then the pickled settings) holds
149
+ the parser keys forwarded to confext plus the sanitize keys:
150
+
151
+ | Key | Default | Used by |
152
+ |---|---|---|
153
+ | `encoding` | `'utf-8'` | Fallback charset for mail parts. |
154
+ | `max_depth` | `100` | confext parse: element nesting cap. |
155
+ | `max_file_size_mb` | `10` | confext parse: input size cap. |
156
+ | `cache_size` | `50` | confext parse: LRU capacity. |
157
+ | `strict_mode` | `False` | confext parse: raise on malformed HTML. |
158
+ | `strip_whitespace` | `True` | confext parse: collapse text whitespace. |
159
+ | `preserve_comments` | `False` | confext parse: keep comments in the tree. |
160
+ | `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`. |
161
+ | `default_tag` | `'div'` | sanitize replacement for non-whitelisted tags. |
162
+ | `remove_scripts` | `True` | sanitize: drop script/style/iframe/object/embed nodes. |
163
+ | `remove_remote_content` | `True` | sanitize: drop remote images/media and remote URL attributes. |
164
+ | `remove_event_handlers` | `True` | sanitize: drop `on*` attributes. |
165
+
166
+ ## Errors
167
+
168
+ ```
169
+ MailReaderError
170
+ ├── ConfigLoadError config file missing/invalid/unsafe/undiscoverable
171
+ ├── SanitizationError malformed sanitize policy
172
+ ╰── SelectorSyntaxError invalid or unsupported selector
173
+
174
+ HTMLParserError (confext) base error of the underlying parser package
175
+ ```
176
+
177
+ All re-exported from the package root (confext's via `import confext`).
178
+
179
+ ## Versioning
180
+
181
+ mailreader follows [semver](https://semver.org/) `MAJOR.MINOR.PATCH`;
182
+ the current version is available as `mailreader.__version__`. Licensed
183
+ under the MIT License — see [LICENSE](LICENSE).
@@ -0,0 +1,47 @@
1
+ from confext.config import (
2
+ CONFIG_NAME,
3
+ PathLike,
4
+ load_config,
5
+ save_config,
6
+ )
7
+ from confext.errors import ConfextError
8
+
9
+ from .exceptions import (
10
+ ConfigLoadError,
11
+ MailReaderError,
12
+ SanitizationError,
13
+ SelectorSyntaxError,
14
+ )
15
+ from .engine import MailReaderEngine, get_config, get_engine, reload
16
+ from .htmlmail import (
17
+ MailDocument,
18
+ mail_to_html,
19
+ parse_mail,
20
+ readable_text,
21
+ select_mail,
22
+ )
23
+
24
+ HTMLParserError = ConfextError
25
+
26
+
27
+ __all__ = [
28
+ '__version__',
29
+ 'CONFIG_NAME',
30
+ 'PathLike',
31
+ 'load_config',
32
+ 'save_config',
33
+ 'MailReaderError',
34
+ 'ConfigLoadError',
35
+ 'SanitizationError',
36
+ 'SelectorSyntaxError',
37
+ 'MailReaderEngine',
38
+ 'get_config',
39
+ 'get_engine',
40
+ 'reload',
41
+ 'MailDocument',
42
+ 'parse_mail',
43
+ 'readable_text',
44
+ 'select_mail',
45
+ 'mail_to_html',
46
+ 'HTMLParserError',
47
+ ]
@@ -0,0 +1,82 @@
1
+ """Config-driven wiring: mailreader's mail engine over the confext parser."""
2
+
3
+ from typing import Any, Dict, Optional, Union
4
+
5
+ from confext import Engine as _ConfextEngine, Node, ParsedDocument
6
+ from confext.config import PathLike, load_config
7
+ from confext.errors import ConfigLoadError as _ConfextConfigLoadError
8
+
9
+ from .exceptions import ConfigLoadError
10
+ from .sanitize import sanitize as _sanitize
11
+
12
+ config: Dict[str, Any] = {}
13
+ _engine: Optional['MailReaderEngine'] = None
14
+ _load_error: Optional[Exception] = None
15
+
16
+ _SANITIZE_KEYS = ('allowed_tags', 'default_tag', 'remove_scripts',
17
+ 'remove_remote_content', 'remove_event_handlers')
18
+
19
+
20
+ class MailReaderEngine(_ConfextEngine):
21
+ """confext.Engine extended with config-driven sanitization for mail HTML."""
22
+
23
+ def sanitize(self, target: Union[str, bytes, Node, ParsedDocument],
24
+ policy: Optional[Dict[str, Any]] = None
25
+ ) -> Union[Node, ParsedDocument]:
26
+ """Sanitize HTML or a document; missing policy keys come from config."""
27
+ doc = self._as_doc(target)
28
+ merged = dict(policy or {})
29
+ for key in _SANITIZE_KEYS:
30
+ if key not in merged and key in self.config:
31
+ merged[key] = self.config[key]
32
+ return _sanitize(doc, merged)
33
+
34
+ def _as_doc(self, target: Union[str, bytes, Node, ParsedDocument]
35
+ ) -> ParsedDocument:
36
+ if isinstance(target, ParsedDocument):
37
+ return target
38
+ if isinstance(target, Node):
39
+ return ParsedDocument(doctype=None, root=target)
40
+ return self.parse(target)
41
+
42
+
43
+ def _ensure() -> None:
44
+ global config, _engine, _load_error
45
+ if _engine is not None:
46
+ return
47
+ try:
48
+ loaded = load_config()
49
+ except (ConfigLoadError, _ConfextConfigLoadError) as exc:
50
+ _load_error = exc
51
+ loaded = None
52
+ config = loaded.to_dict() if loaded is not None else {}
53
+ _engine = MailReaderEngine(config)
54
+
55
+ _ensure()
56
+
57
+
58
+ def get_config() -> Dict[str, Any]:
59
+ """Return the active configuration dict (lazy-loaded)."""
60
+ return config
61
+
62
+
63
+ def get_engine() -> MailReaderEngine:
64
+ """Return the active mailreader engine built from default.config."""
65
+ return _engine
66
+
67
+
68
+ def reload(path: Optional[PathLike] = None) -> Dict[str, Any]:
69
+ """Load (or reload) a config and rebuild the active engine.
70
+
71
+ No path reloads the bundled default.config; a path adopts that file.
72
+ Raises ConfigLoadError for a missing, invalid, or unsafe file.
73
+ """
74
+ global config, _engine, _load_error
75
+ try:
76
+ cfg = load_config(path)
77
+ except _ConfextConfigLoadError as exc:
78
+ raise ConfigLoadError(str(exc)) from exc
79
+ config = cfg.to_dict()
80
+ _engine = MailReaderEngine(config)
81
+ _load_error = None
82
+ return config
@@ -0,0 +1,14 @@
1
+ class MailReaderError(Exception):
2
+ """Base class for all mailreader errors."""
3
+
4
+
5
+ class ConfigLoadError(MailReaderError):
6
+ """Config file missing, invalid, unsafe, or not discoverable."""
7
+
8
+
9
+ class SanitizationError(MailReaderError):
10
+ """Reserved for future sanitization failures."""
11
+
12
+
13
+ class SelectorSyntaxError(MailReaderError):
14
+ """Reserved for future selector parsing failures."""
@@ -0,0 +1,35 @@
1
+ """Internal extraction helpers over confext trees: selector find and text."""
2
+
3
+ from typing import Optional, Union
4
+
5
+ from confext import Node, ParsedDocument
6
+ from confext.tree import normalize_ws
7
+
8
+ from .engine import get_engine
9
+ from .selectors import find_all as _find_all
10
+
11
+ Target = Union[str, bytes, Node, ParsedDocument]
12
+
13
+
14
+ def _target_doc(target: Target) -> ParsedDocument:
15
+ if isinstance(target, ParsedDocument):
16
+ return target
17
+ if isinstance(target, Node):
18
+ return ParsedDocument(doctype=None, root=target)
19
+ return get_engine().parse(target)
20
+
21
+
22
+ def find_all(target: Target, selector: str):
23
+ """All elements matching a CSS selector, in document order."""
24
+ return _find_all(_target_doc(target).root, selector)
25
+
26
+
27
+ def text(target: Target, selector: Optional[str] = None) -> str:
28
+ """Whitespace-normalized text of the document or of selector matches."""
29
+ doc = _target_doc(target)
30
+ if selector:
31
+ matches = _find_all(doc.root, selector)
32
+ return ' '.join(
33
+ normalize_ws(m.text_content()).strip() for m in matches
34
+ ).strip()
35
+ return normalize_ws(doc.root.text_content()).strip()