mailreader 2.7.1__py3-none-any.whl

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.
mailreader/__init__.py ADDED
@@ -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
+ ]
Binary file
mailreader/engine.py ADDED
@@ -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."""
mailreader/extract.py ADDED
@@ -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()
mailreader/htmlmail.py ADDED
@@ -0,0 +1,190 @@
1
+ """HTML mail parsing: extract, decode, parse, sanitize."""
2
+
3
+ import codecs
4
+ import re
5
+ from email import policy as _email_policy
6
+ from email.parser import BytesParser as _BytesParser
7
+ from html import escape as _escape
8
+ from typing import Any, Dict, List, Optional, Union
9
+
10
+ from confext import ParsedDocument
11
+
12
+ from .engine import get_engine
13
+ from .extract import find_all as _find_all, text as _extract_text
14
+
15
+ _QUOTED_LINE = re.compile(r'^\s*>')
16
+ _SIGNATURE = re.compile(r'^-- ?$')
17
+ _BLANK_RUN = re.compile(r'\n{3,}')
18
+ _PARAGRAPH_SPLIT = re.compile(r'\n\s*\n')
19
+ _URL = re.compile(r'https?://[^\s<>"\']+')
20
+
21
+
22
+ class MailDocument:
23
+ """Structured result of parsing a mail message."""
24
+
25
+ def __init__(self, headers: Dict[str, str], html: Optional[ParsedDocument],
26
+ text: str, parts: List[Dict[str, Any]],
27
+ attachments: List[Dict[str, Any]],
28
+ inline_images: List[Dict[str, Any]],
29
+ config: Optional[Dict[str, Any]] = None) -> None:
30
+ self.headers = headers
31
+ self.html = html
32
+ self.text = text
33
+ self.parts = parts
34
+ self.attachments = attachments
35
+ self.inline_images = inline_images
36
+ self.config = config or {}
37
+
38
+ @property
39
+ def subject(self) -> str:
40
+ return self.headers.get('Subject', '')
41
+
42
+ @property
43
+ def from_(self) -> str:
44
+ return self.headers.get('From', '')
45
+
46
+ def to_dict(self) -> Dict[str, Any]:
47
+ return {
48
+ 'headers': dict(self.headers),
49
+ 'subject': self.subject,
50
+ 'from': self.from_,
51
+ 'text': self.text,
52
+ 'html': self.html.to_html() if self.html is not None else '',
53
+ 'stats': self.html.stats() if self.html is not None else {},
54
+ 'parts': list(self.parts),
55
+ 'attachments': list(self.attachments),
56
+ 'inline_images': list(self.inline_images),
57
+ }
58
+
59
+ def __repr__(self) -> str:
60
+ return f'<MailDocument {self.subject!r}>'
61
+
62
+
63
+ def parse_mail(raw: Union[str, bytes],
64
+ include_payload: bool = False) -> MailDocument:
65
+ """Parse a raw mail message into a sanitized, structured document."""
66
+ engine = get_engine()
67
+ if isinstance(raw, str):
68
+ raw = raw.encode('utf-8')
69
+ message = _BytesParser(policy=_email_policy.default).parsebytes(raw)
70
+
71
+ headers: Dict[str, str] = {}
72
+ for name, value in message.items():
73
+ name, value = str(name), str(value)
74
+ headers[name] = (
75
+ f'{headers[name]}, {value}' if name in headers else value
76
+ )
77
+
78
+ html_source: Optional[str] = None
79
+ plain_source: Optional[str] = None
80
+ parts: List[Dict[str, Any]] = []
81
+ attachments: List[Dict[str, Any]] = []
82
+ inline_images: List[Dict[str, Any]] = []
83
+
84
+ for part in message.walk():
85
+ if part.is_multipart():
86
+ continue
87
+ ctype = part.get_content_type()
88
+ disposition = part.get_content_disposition() or 'inline'
89
+ filename = part.get_filename()
90
+ cid = part.get('Content-ID')
91
+ if cid:
92
+ cid = str(cid).strip('<>')
93
+ payload = part.get_payload(decode=True)
94
+ if payload is None:
95
+ payload = str(part.get_payload() or '').encode(
96
+ 'utf-8', errors='replace'
97
+ )
98
+ charset = _charset_for(part, engine.config)
99
+ meta = {
100
+ 'content_type': ctype,
101
+ 'charset': charset,
102
+ 'disposition': disposition,
103
+ 'filename': filename,
104
+ 'content_id': cid,
105
+ 'size': len(payload),
106
+ }
107
+ parts.append(dict(meta))
108
+ if disposition == 'attachment' or filename:
109
+ if include_payload:
110
+ meta['payload'] = payload
111
+ attachments.append(dict(meta))
112
+ elif ctype == 'text/html' and html_source is None:
113
+ html_source = payload.decode(charset, errors='replace')
114
+ elif ctype == 'text/plain' and plain_source is None:
115
+ plain_source = payload.decode(charset, errors='replace')
116
+ elif ctype.startswith('image/') and cid:
117
+ inline_images.append(dict(meta))
118
+
119
+ if html_source is None and plain_source is not None:
120
+ html_source = _plain_to_html(plain_source)
121
+ if html_source is not None:
122
+ doc: Optional[ParsedDocument] = engine.sanitize(engine.parse(html_source))
123
+ else:
124
+ doc = engine.parse('<html><body></body></html>')
125
+
126
+ text = plain_source if plain_source is not None else _extract_text(doc)
127
+ return MailDocument(
128
+ headers=headers,
129
+ html=doc,
130
+ text=_tidy_text(text),
131
+ parts=parts,
132
+ attachments=attachments,
133
+ inline_images=inline_images,
134
+ config=dict(engine.config),
135
+ )
136
+
137
+
138
+ def readable_text(raw: Union[str, bytes]) -> str:
139
+ """Extract readable plain text, stripping quoted replies and signatures."""
140
+ return parse_mail(raw).text
141
+
142
+
143
+ def select_mail(raw: Union[str, bytes], selector: str) -> List[Dict[str, Any]]:
144
+ """Run a CSS selector over the sanitized HTML of a mail message."""
145
+ doc = parse_mail(raw).html
146
+ if doc is None:
147
+ return []
148
+ return [node.to_dict() for node in _find_all(doc, selector)]
149
+
150
+
151
+ def mail_to_html(raw: Union[str, bytes]) -> str:
152
+ """Return the sanitized HTML of a mail message as a string."""
153
+ doc = parse_mail(raw).html
154
+ return doc.to_html() if doc is not None else ''
155
+
156
+
157
+ def _charset_for(part, config: Dict[str, Any]) -> str:
158
+ charset = part.get_content_charset()
159
+ if charset:
160
+ try:
161
+ codecs.lookup(charset)
162
+ return charset
163
+ except (LookupError, TypeError):
164
+ pass
165
+ return str(config.get('encoding', 'utf-8') or 'utf-8')
166
+
167
+
168
+ def _tidy_text(text: str) -> str:
169
+ kept: List[str] = []
170
+ for line in text.splitlines():
171
+ if _QUOTED_LINE.match(line):
172
+ continue
173
+ if _SIGNATURE.match(line):
174
+ break
175
+ kept.append(line.rstrip())
176
+ tidied = _BLANK_RUN.sub('\n\n', '\n'.join(kept))
177
+ return tidied.strip()
178
+
179
+
180
+ def _plain_to_html(text: str) -> str:
181
+ rendered: List[str] = []
182
+ for paragraph in _PARAGRAPH_SPLIT.split(text):
183
+ if not paragraph.strip():
184
+ continue
185
+ escaped = _escape(paragraph.strip())
186
+ escaped = _URL.sub(
187
+ lambda m: f'<a href="{m.group(0)}">{m.group(0)}</a>', escaped
188
+ )
189
+ rendered.append(f'<p>{escaped.replace(chr(10), "<br>")}</p>')
190
+ return '\n'.join(rendered) or '<p></p>'
mailreader/sanitize.py ADDED
@@ -0,0 +1,108 @@
1
+ """Policy-driven HTML sanitization as a tree transform."""
2
+
3
+ from typing import Any, Dict, Optional, Union
4
+
5
+ from confext import Node, ParsedDocument
6
+
7
+ from .exceptions import SanitizationError
8
+
9
+ _REMOTE_PREFIXES = ('http://', 'https://', '//')
10
+ _URL_ATTRS = ('src', 'href', 'action', 'formaction', 'poster', 'background',
11
+ 'cite', 'data')
12
+ _SCRIPT_TAGS = ('script', 'style', 'iframe', 'object', 'embed', 'applet')
13
+ _REMOTE_NODE_TAGS = ('img', 'source', 'iframe', 'video', 'audio', 'track')
14
+ _FLAG_KEYS = ('remove_scripts', 'remove_event_handlers', 'remove_remote_content')
15
+
16
+ DEFAULT_POLICY: Dict[str, Any] = {
17
+ 'remove_scripts': True,
18
+ 'remove_event_handlers': True,
19
+ 'remove_remote_content': True,
20
+ 'allowed_tags': None,
21
+ 'default_tag': None,
22
+ }
23
+
24
+
25
+ def normalize_policy(policy: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
26
+ merged = dict(DEFAULT_POLICY)
27
+ if policy is not None:
28
+ if not isinstance(policy, dict):
29
+ raise SanitizationError(
30
+ f'policy must be a dict, got {type(policy).__name__}'
31
+ )
32
+ merged.update(policy)
33
+ for key in _FLAG_KEYS:
34
+ value = merged.get(key)
35
+ if value is not None and not isinstance(value, bool):
36
+ raise SanitizationError(f'{key} must be a boolean, got {value!r}')
37
+ allowed = merged.get('allowed_tags')
38
+ if allowed is not None:
39
+ if isinstance(allowed, str):
40
+ raise SanitizationError(
41
+ 'allowed_tags must be a list/set of tags, not a string'
42
+ )
43
+ try:
44
+ merged['allowed_tags'] = {str(tag).lower() for tag in allowed}
45
+ except TypeError:
46
+ raise SanitizationError(
47
+ 'allowed_tags must be an iterable of tag names'
48
+ ) from None
49
+ default_tag = merged.get('default_tag')
50
+ if default_tag is not None and not isinstance(default_tag, str):
51
+ raise SanitizationError(
52
+ f'default_tag must be a string, got {default_tag!r}'
53
+ )
54
+ return merged
55
+
56
+
57
+ def sanitize(target: Union[Node, ParsedDocument],
58
+ policy: Optional[Dict[str, Any]] = None
59
+ ) -> Union[Node, ParsedDocument]:
60
+ """Sanitize a Node or ParsedDocument in place and return it."""
61
+ merged = normalize_policy(policy)
62
+ root = target.root if isinstance(target, ParsedDocument) else target
63
+ _clean(root, merged)
64
+ return target
65
+
66
+
67
+ def _clean(root: Node, policy: Dict[str, Any]) -> None:
68
+ for child in list(root.children):
69
+ if isinstance(child, str) or child.is_comment:
70
+ continue
71
+ _clean(child, policy)
72
+ if _drop_node(child, policy):
73
+ child.remove()
74
+
75
+
76
+ def _drop_node(node: Node, policy: Dict[str, Any]) -> bool:
77
+ if policy['remove_scripts'] and node.tag in _SCRIPT_TAGS:
78
+ return True
79
+ if policy['remove_remote_content'] and node.tag in _REMOTE_NODE_TAGS:
80
+ src = node.get_attr('src')
81
+ if src and src.lower().startswith(_REMOTE_PREFIXES):
82
+ return True
83
+ _strip_attrs(node, policy)
84
+ allowed = policy['allowed_tags']
85
+ if allowed is not None and node.tag not in allowed:
86
+ default_tag = policy.get('default_tag')
87
+ if default_tag:
88
+ node.tag = str(default_tag).lower()
89
+ else:
90
+ return True
91
+ return False
92
+
93
+
94
+ def _strip_attrs(node: Node, policy: Dict[str, Any]) -> None:
95
+ for name in list(node.attrs):
96
+ value = node.attrs[name]
97
+ lowered = name.lower()
98
+ if policy['remove_event_handlers'] and lowered.startswith('on'):
99
+ del node.attrs[name]
100
+ continue
101
+ if lowered in _URL_ATTRS and isinstance(value, str):
102
+ stripped = value.strip().lower()
103
+ if stripped.startswith('javascript:'):
104
+ del node.attrs[name]
105
+ continue
106
+ if (policy['remove_remote_content']
107
+ and value.startswith(_REMOTE_PREFIXES)):
108
+ del node.attrs[name]
@@ -0,0 +1,288 @@
1
+ """CSS selector engine: compounds, combinators, pseudo-classes."""
2
+
3
+ import re
4
+ from typing import Any, List, Optional, Tuple
5
+
6
+ from confext.tree import ROOT_TAG, Node
7
+
8
+ from .exceptions import SelectorSyntaxError
9
+
10
+ _GroupToken = re.compile(
11
+ r'''\[[^\]]*\]|"[^"]*"|'[^']*'|\([^()]*\)|[>+~]|\s+|[^\[\]()"'\s>+~]+'''
12
+ )
13
+ _CompoundToken = re.compile(
14
+ r'''\[\s*[A-Za-z_][-\w:]*\s*(?:[~^$*|]?=\s*(?:"[^"]*"|'[^']*'|[^\]\s]+))?\s*\]'''
15
+ r'''|#[\w-]+'''
16
+ r'''|\.[-\w]+'''
17
+ r'''|:[\w-]+(?:\([^()]*\))?'''
18
+ )
19
+ _Tag = re.compile(r'[A-Za-z][-\w]*')
20
+
21
+ _SUPPORTED_PSEUDOS = {'first-child', 'last-child', 'nth-child'}
22
+
23
+ Compound = Tuple[str, Optional[str], Tuple[str, ...],
24
+ Tuple[Tuple[str, Optional[str], Optional[str]], ...],
25
+ Tuple[Tuple[str, Any, Optional[Any]], ...]]
26
+
27
+
28
+ def _parse_nth(arg: Optional[str]) -> Tuple[int, int]:
29
+ if arg is None:
30
+ raise SelectorSyntaxError('nth-child requires an argument')
31
+ text = arg.replace(' ', '').lower()
32
+ if text == 'odd':
33
+ return (2, 1)
34
+ if text == 'even':
35
+ return (2, 0)
36
+ if re.match(r'^[+-]?\d+$', text):
37
+ return (0, int(text))
38
+ match = re.match(r'^([+-]?\d*)n([+-]\d+)?$', text)
39
+ if match:
40
+ raw = match.group(1)
41
+ if raw in ('', '+'):
42
+ step = 1
43
+ elif raw == '-':
44
+ step = -1
45
+ else:
46
+ step = int(raw)
47
+ return (step, int(match.group(2) or 0))
48
+ raise SelectorSyntaxError(f'invalid nth-child argument: {arg!r}')
49
+
50
+
51
+ def _parse_compound(part: str) -> Compound:
52
+ """Parse 'div#id.cls[attr=val]:first-child' into its parts."""
53
+ if part == '*':
54
+ return ('*', None, (), (), ())
55
+ match = _Tag.match(part)
56
+ tag = match.group(0) if match else '*'
57
+ rest = part[match.end():] if match else part
58
+ node_id: Optional[str] = None
59
+ classes: List[str] = []
60
+ attrs: List[Tuple[str, Optional[str], Optional[str]]] = []
61
+ pseudos: List[Tuple[str, Any]] = []
62
+ pos = 0
63
+ for token in _CompoundToken.finditer(rest):
64
+ if token.start() != pos:
65
+ break
66
+ pos = token.end()
67
+ chunk = token.group(0)
68
+ if chunk.startswith('#'):
69
+ node_id = chunk[1:]
70
+ elif chunk.startswith('.'):
71
+ classes.append(chunk[1:])
72
+ elif chunk.startswith(':'):
73
+ inner = re.match(r'^([\w-]+)(?:\((.*)\))?$', chunk[1:])
74
+ if not inner:
75
+ raise SelectorSyntaxError(f'invalid pseudo-class: {chunk!r}')
76
+ name = inner.group(1).lower()
77
+ if name not in _SUPPORTED_PSEUDOS:
78
+ raise SelectorSyntaxError(f'unsupported pseudo-class: {chunk!r}')
79
+ arg = inner.group(2)
80
+ pseudos.append(
81
+ (name, _parse_nth(arg) if name == 'nth-child' else None)
82
+ )
83
+ else:
84
+ inner = chunk[1:-1].strip()
85
+ attr = re.match(r'([-\w:]+)(?:\s*([~^$*|]?=)\s*(.*))?$',
86
+ inner, re.DOTALL)
87
+ name, op, raw = attr.group(1), attr.group(2), attr.group(3)
88
+ if raw is not None:
89
+ raw = raw.strip()
90
+ if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in ('"', "'"):
91
+ raw = raw[1:-1]
92
+ attrs.append((name, op, raw))
93
+ if pos != len(rest):
94
+ raise SelectorSyntaxError(f'invalid selector compound: {part!r}')
95
+ return (tag, node_id, tuple(classes), tuple(attrs), tuple(pseudos))
96
+
97
+
98
+ def _split_groups(selector: str) -> List[str]:
99
+ groups: List[str] = []
100
+ buf: List[str] = []
101
+ depth = 0
102
+ quote = None
103
+ for ch in selector:
104
+ if quote:
105
+ buf.append(ch)
106
+ if ch == quote:
107
+ quote = None
108
+ elif ch in ('"', "'"):
109
+ quote = ch
110
+ buf.append(ch)
111
+ elif ch == '[':
112
+ depth += 1
113
+ buf.append(ch)
114
+ elif ch == ']':
115
+ depth = max(0, depth - 1)
116
+ buf.append(ch)
117
+ elif ch == ',' and depth == 0:
118
+ groups.append(''.join(buf))
119
+ buf = []
120
+ else:
121
+ buf.append(ch)
122
+ groups.append(''.join(buf))
123
+ return [g for g in (g.strip() for g in groups) if g]
124
+
125
+
126
+ def _parse_group(group: str) -> List[Tuple[Optional[str], Compound]]:
127
+ tokens = _GroupToken.findall(group)
128
+ if ''.join(tokens) != group:
129
+ raise SelectorSyntaxError(f'invalid selector: {group!r}')
130
+ chain: List[Tuple[Optional[str], Compound]] = []
131
+ parts: List[str] = []
132
+ comb: Optional[str] = None
133
+ seen_ws = False
134
+ for tok in tokens:
135
+ if tok in ('>', '+', '~'):
136
+ if not parts:
137
+ raise SelectorSyntaxError(f'misplaced combinator in selector: {group!r}')
138
+ chain.append((comb, _parse_compound(''.join(parts))))
139
+ parts = []
140
+ comb = tok
141
+ seen_ws = False
142
+ elif not tok.strip():
143
+ seen_ws = True
144
+ else:
145
+ if parts and seen_ws:
146
+ chain.append((comb, _parse_compound(''.join(parts))))
147
+ parts = []
148
+ comb = ' '
149
+ parts.append(tok)
150
+ seen_ws = False
151
+ if not parts:
152
+ raise SelectorSyntaxError(f'invalid or empty selector: {group!r}')
153
+ chain.append((comb, _parse_compound(''.join(parts))))
154
+ return chain
155
+
156
+
157
+ def _attr_matches(op: str, actual: str, expected: Optional[str]) -> bool:
158
+ if op == '=':
159
+ return actual == expected
160
+ if op == '^=':
161
+ return bool(expected) and actual.startswith(expected)
162
+ if op == '$=':
163
+ return bool(expected) and actual.endswith(expected)
164
+ if op == '*=':
165
+ return bool(expected) and expected in actual
166
+ if op == '~=':
167
+ return bool(expected) and expected in actual.split()
168
+ if op == '|=':
169
+ return actual == expected or actual.startswith((expected or '\0') + '-')
170
+ return False
171
+
172
+
173
+ def _prev_element_siblings(node: Node):
174
+ parent = node.parent
175
+ if parent is None:
176
+ return
177
+ found = False
178
+ for child in reversed(parent.children):
179
+ if child is node:
180
+ found = True
181
+ continue
182
+ if found and isinstance(child, Node) and not child.is_comment:
183
+ yield child
184
+
185
+
186
+ def _next_element_sibling(node: Node) -> Optional[Node]:
187
+ parent = node.parent
188
+ if parent is None:
189
+ return None
190
+ found = False
191
+ for child in parent.children:
192
+ if child is node:
193
+ found = True
194
+ continue
195
+ if found and isinstance(child, Node) and not child.is_comment:
196
+ return child
197
+ return None
198
+
199
+
200
+ def _element_index(node: Node) -> int:
201
+ parent = node.parent
202
+ if parent is None:
203
+ return 1
204
+ index = 0
205
+ for child in parent.children:
206
+ if isinstance(child, Node) and not child.is_comment:
207
+ index += 1
208
+ if child is node:
209
+ return index
210
+ return index
211
+
212
+
213
+ def _pseudo_matches(node: Node, name: str, arg: Any) -> bool:
214
+ if name == 'first-child':
215
+ return next(iter(_prev_element_siblings(node)), None) is None
216
+ if name == 'last-child':
217
+ return _next_element_sibling(node) is None
218
+ step, offset = arg
219
+ index = _element_index(node)
220
+ if step == 0:
221
+ return index == offset
222
+ delta = index - offset
223
+ return delta % step == 0 and delta // step >= 0
224
+
225
+
226
+ def _matches_compound(node: Node, compound: Compound) -> bool:
227
+ if node.is_comment or node.tag == ROOT_TAG:
228
+ return False
229
+ tag, node_id, classes, attrs, pseudos = compound
230
+ if tag != '*' and node.tag != tag:
231
+ return False
232
+ if node_id is not None and node.get_attr('id') != node_id:
233
+ return False
234
+ if any(not node.has_class(cls) for cls in classes):
235
+ return False
236
+ for name, op, expected in attrs:
237
+ actual = node.attrs.get(name)
238
+ if actual is None:
239
+ return False
240
+ if op is not None and not _attr_matches(op, actual, expected):
241
+ return False
242
+ return all(_pseudo_matches(node, name, arg) for name, arg in pseudos)
243
+
244
+
245
+ def _match_chain(node: Node, chain: List[Tuple[Optional[str], Compound]]) -> bool:
246
+ comb, compound = chain[-1]
247
+ if not _matches_compound(node, compound):
248
+ return False
249
+ rest = chain[:-1]
250
+ if not rest:
251
+ return True
252
+ if comb == ' ':
253
+ ancestor = node.parent
254
+ while ancestor is not None:
255
+ if _match_chain(ancestor, rest):
256
+ return True
257
+ ancestor = ancestor.parent
258
+ return False
259
+ if comb == '>':
260
+ parent = node.parent
261
+ return parent is not None and _match_chain(parent, rest)
262
+ if comb == '+':
263
+ sibling = next(iter(_prev_element_siblings(node)), None)
264
+ return sibling is not None and _match_chain(sibling, rest)
265
+ for sibling in _prev_element_siblings(node):
266
+ if _match_chain(sibling, rest):
267
+ return True
268
+ return False
269
+
270
+
271
+ def find_all(root: Node, selector: str) -> List[Node]:
272
+ """Find elements matching a CSS selector, in document order."""
273
+ groups = _split_groups(selector)
274
+ if not groups:
275
+ raise SelectorSyntaxError(f'empty selector: {selector!r}')
276
+ chains = [_parse_group(group) for group in groups]
277
+ matches: List[Node] = []
278
+ seen: set = set()
279
+ for chain in chains:
280
+ for node in root.iter_elements():
281
+ if id(node) not in seen and _match_chain(node, chain):
282
+ seen.add(id(node))
283
+ matches.append(node)
284
+ return matches
285
+
286
+
287
+ def find(root: Node, selector: str) -> Optional[Node]:
288
+ return next(iter(find_all(root, selector)), None)
@@ -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,13 @@
1
+ mailreader/__init__.py,sha256=qGoBlrH9-bvsga8WQaxjLCLOuspyYZgkdKcyCK_sKW8,871
2
+ mailreader/default.config,sha256=GcxHrtSg0UbL89Rw914fYJ-FMyzWIGPRLg8cInKxtW0,5715
3
+ mailreader/engine.py,sha256=9WLwxGpGwQCf71ynfHZQlxslcNqnWwkpbpHzMO9fzBI,2768
4
+ mailreader/exceptions.py,sha256=c5w1TLA9XhapTj9pAb2rcRJqviJ-tiy4XO_Zfyex12Y,393
5
+ mailreader/extract.py,sha256=iZ8NnN3UD77dnZPZ2XqAR8vhq07XASz9ERbRJw-wEFs,1145
6
+ mailreader/htmlmail.py,sha256=x8avUPlI8Q2xFKIjU0FtUvi4-hs3sV-6PWyu77ofvDY,6415
7
+ mailreader/sanitize.py,sha256=dUPaBbfc3cdqbs2FlhfUmY4f6XGEcxESBiEqq-fRqfc,3941
8
+ mailreader/selectors.py,sha256=BMHSEYCn1H7F9HNZD6U8R6BLYlj0SoXRTiEwkFSxg78,9515
9
+ mailreader-2.7.1.dist-info/licenses/LICENSE,sha256=virJzXfbJzfgXvyERda_5p3kZUkGS2AO9no5Dt5o0aU,1082
10
+ mailreader-2.7.1.dist-info/METADATA,sha256=OWTN6zN9F1zFRt6ehNl4PKf0a1fE_g99s6tUkVVAEXg,9361
11
+ mailreader-2.7.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
12
+ mailreader-2.7.1.dist-info/top_level.txt,sha256=k7qKQ01OKUixQ7PLY_oZo5ES13tCC8vMz8z5jwuDulY,11
13
+ mailreader-2.7.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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 @@
1
+ mailreader