email-forward-parser 0.2.2__tar.gz → 0.2.4__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.
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/.githooks/pre-push +7 -1
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/.github/workflows/workflow.yml +1 -1
- email_forward_parser-0.2.4/.python-version +1 -0
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/PKG-INFO +7 -2
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/README.md +5 -1
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/emailforwardparser/client.py +116 -8
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/emailforwardparser/utils.py +11 -1
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/pyproject.toml +10 -9
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/tests/coverage_edges_test.py +10 -0
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/tests/regressions_test.py +91 -0
- email_forward_parser-0.2.4/uv.lock +506 -0
- email_forward_parser-0.2.2/uv.lock +0 -495
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/.github/dependabot.yml +0 -0
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/.github/workflows/ci.yml +0 -0
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/.gitignore +0 -0
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/LICENSE +0 -0
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/NOTICE +0 -0
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/emailforwardparser/__init__.py +0 -0
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/emailforwardparser/forward_parser.py +0 -0
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/emailforwardparser/literals.py +0 -0
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/emailforwardparser/loop.py +0 -0
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/emailforwardparser/regexs.py +0 -0
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/tests/__init__.py +0 -0
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/tests/client_test.py +0 -0
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/tests/forward_parser_test.py +0 -0
- {email_forward_parser-0.2.2 → email_forward_parser-0.2.4}/tests/literals_test.py +0 -0
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
#!/bin/sh
|
|
2
|
-
# Style and
|
|
2
|
+
# Style, type and test checks on the commits being pushed, on the newest Python (.python-version); GitHub Actions
|
|
3
|
+
# runs the tests on the oldest one the package supports.
|
|
3
4
|
# Turn it on once per clone: git config core.hooksPath .githooks
|
|
4
5
|
|
|
5
6
|
fix='uv run black . && uv run isort . && uv run ruff check --fix .'
|
|
@@ -14,6 +15,11 @@ checks() {
|
|
|
14
15
|
check uv run isort --check-only .
|
|
15
16
|
check uv run ruff check .
|
|
16
17
|
check uv run mypy
|
|
18
|
+
# The coverage gate runs with the JIT off: under it, CPython 3.15 reports a loop's exit branch from the wrong
|
|
19
|
+
# instruction (coveragepy/coveragepy#2249). Callers may run Python with the JIT on, so the suite runs again
|
|
20
|
+
# under it, without coverage.
|
|
21
|
+
check env PYTHON_JIT=0 uv run pytest
|
|
22
|
+
check env PYTHON_JIT=1 uv run pytest --no-cov
|
|
17
23
|
}
|
|
18
24
|
|
|
19
25
|
# --- the same in every repo from here ---
|
|
@@ -98,7 +98,7 @@ jobs:
|
|
|
98
98
|
path: dist/
|
|
99
99
|
|
|
100
100
|
- name: Publish release
|
|
101
|
-
uses: softprops/action-gh-release@
|
|
101
|
+
uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4
|
|
102
102
|
with:
|
|
103
103
|
files: dist/*
|
|
104
104
|
generate_release_notes: true
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
3.15
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: email-forward-parser
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.4
|
|
4
4
|
Summary: Python Library to parse forwarded email messages
|
|
5
5
|
Project-URL: Homepage, https://github.com/felipehertzer/email-forward-parser-py
|
|
6
6
|
Project-URL: Repository, https://github.com/felipehertzer/email-forward-parser-py
|
|
@@ -213,6 +213,7 @@ Classifier: License :: OSI Approved :: Apache Software License
|
|
|
213
213
|
Classifier: Operating System :: OS Independent
|
|
214
214
|
Classifier: Programming Language :: Python :: 3
|
|
215
215
|
Classifier: Programming Language :: Python :: 3.14
|
|
216
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
216
217
|
Classifier: Topic :: Communications :: Email
|
|
217
218
|
Classifier: Topic :: Text Processing
|
|
218
219
|
Requires-Python: >=3.14
|
|
@@ -524,7 +525,11 @@ python -m mypy
|
|
|
524
525
|
python -m pytest
|
|
525
526
|
```
|
|
526
527
|
|
|
527
|
-
`pytest` is configured to require 100% statement and branch coverage.
|
|
528
|
+
`pytest` is configured to require 100% statement and branch coverage. On Python 3.15,
|
|
529
|
+
measure it with the JIT off (`PYTHON_JIT=0 python -m pytest`): with the JIT on, CPython
|
|
530
|
+
3.15 reports some branches from the wrong instruction (coveragepy/coveragepy#2249). The
|
|
531
|
+
pre-push hook runs the gate that way, then the suite again with `PYTHON_JIT=1` and
|
|
532
|
+
`--no-cov`.
|
|
528
533
|
|
|
529
534
|
`emailforwardparser/literals.py` lists the text each pattern in `regexs.py` needs
|
|
530
535
|
before it can match, so a pattern is not run on a string without it. After changing
|
|
@@ -304,7 +304,11 @@ python -m mypy
|
|
|
304
304
|
python -m pytest
|
|
305
305
|
```
|
|
306
306
|
|
|
307
|
-
`pytest` is configured to require 100% statement and branch coverage.
|
|
307
|
+
`pytest` is configured to require 100% statement and branch coverage. On Python 3.15,
|
|
308
|
+
measure it with the JIT off (`PYTHON_JIT=0 python -m pytest`): with the JIT on, CPython
|
|
309
|
+
3.15 reports some branches from the wrong instruction (coveragepy/coveragepy#2249). The
|
|
310
|
+
pre-push hook runs the gate that way, then the suite again with `PYTHON_JIT=1` and
|
|
311
|
+
`--no-cov`.
|
|
308
312
|
|
|
309
313
|
`emailforwardparser/literals.py` lists the text each pattern in `regexs.py` needs
|
|
310
314
|
before it can match, so a pattern is not run on a string without it. After changing
|
|
@@ -2,16 +2,20 @@ from __future__ import annotations
|
|
|
2
2
|
|
|
3
3
|
import base64
|
|
4
4
|
import binascii
|
|
5
|
+
import copy
|
|
5
6
|
import logging
|
|
7
|
+
import re
|
|
6
8
|
from email import policy
|
|
7
9
|
from email.errors import HeaderParseError
|
|
8
10
|
from email.header import decode_header, make_header
|
|
11
|
+
from email.headerregistry import BaseHeader, HeaderRegistry
|
|
9
12
|
from email.message import EmailMessage, Message
|
|
10
13
|
from email.mime.multipart import MIMEMultipart
|
|
11
14
|
from email.mime.text import MIMEText
|
|
12
15
|
from email.parser import Parser
|
|
13
|
-
from email.
|
|
14
|
-
from
|
|
16
|
+
from email.policy import EmailPolicy
|
|
17
|
+
from email.utils import formataddr, getaddresses, parsedate_to_datetime
|
|
18
|
+
from typing import TypedDict, cast
|
|
15
19
|
|
|
16
20
|
from emailforwardparser import forward_parser as fp
|
|
17
21
|
|
|
@@ -22,6 +26,16 @@ ParsedEmail = TypedDict(
|
|
|
22
26
|
|
|
23
27
|
LOGGER = logging.getLogger(__name__)
|
|
24
28
|
|
|
29
|
+
# The transfer encodings of text: a part with neither holds 8-bit text as written.
|
|
30
|
+
TRANSFER_ENCODINGS = ("quoted-printable", "base64")
|
|
31
|
+
|
|
32
|
+
# The characters for which formataddr() quotes a name, and those it escapes in the quotes.
|
|
33
|
+
NAME_SPECIALS = re.compile(r'[][\\()<>@,:;".]')
|
|
34
|
+
NAME_ESCAPES = re.compile(r'[\\"]')
|
|
35
|
+
|
|
36
|
+
# Builds every header as unstructured text.
|
|
37
|
+
TEXT_HEADERS = HeaderRegistry(use_default_map=False)
|
|
38
|
+
|
|
25
39
|
|
|
26
40
|
class EmailParserClient:
|
|
27
41
|
"""
|
|
@@ -126,13 +140,14 @@ class EmailParserClient:
|
|
|
126
140
|
def _build_original_email(
|
|
127
141
|
self, metadata: fp.OriginalMetadata, message: Message
|
|
128
142
|
) -> EmailMessage | MIMEMultipart:
|
|
143
|
+
rebuilt_policy = self._rebuilt_policy(metadata)
|
|
129
144
|
if not message.is_multipart():
|
|
130
|
-
result_message = EmailMessage()
|
|
145
|
+
result_message = EmailMessage(policy=rebuilt_policy)
|
|
131
146
|
self._set_headers(metadata, result_message)
|
|
132
147
|
result_message.set_content(metadata.body or "")
|
|
133
148
|
return result_message
|
|
134
149
|
|
|
135
|
-
result = MIMEMultipart()
|
|
150
|
+
result = MIMEMultipart(policy=rebuilt_policy)
|
|
136
151
|
self._set_headers(metadata, result)
|
|
137
152
|
|
|
138
153
|
mt = MIMEText(metadata.body or "", _subtype="plain", _charset="utf-8")
|
|
@@ -157,9 +172,22 @@ class EmailParserClient:
|
|
|
157
172
|
result.attach(part)
|
|
158
173
|
return result
|
|
159
174
|
|
|
175
|
+
def _rebuilt_policy(self, metadata: fp.OriginalMetadata) -> EmailPolicy[EmailMessage]:
|
|
176
|
+
"""The policy the original email is written with: `policy.default`, with UTF-8 headers
|
|
177
|
+
(RFC 6532) when a header that cannot hold an encoded word is not ASCII: an address, a
|
|
178
|
+
name without an address (which the header holds as written), or a date. The default
|
|
179
|
+
policy refuses to write such an address (HeaderWriteError).
|
|
180
|
+
"""
|
|
181
|
+
addresses = [
|
|
182
|
+
self._format_addresses(m) for m in ([metadata.from_], metadata.to, metadata.cc)
|
|
183
|
+
]
|
|
184
|
+
return policy.default.clone(
|
|
185
|
+
utf8=not all(header.isascii() for header in [metadata.date, *addresses])
|
|
186
|
+
)
|
|
187
|
+
|
|
160
188
|
def _set_headers(self, metadata: fp.OriginalMetadata, result: EmailMessage | Message) -> None:
|
|
161
189
|
if metadata.date:
|
|
162
|
-
result["Date"] = self._header_value(metadata.date)
|
|
190
|
+
result["Date"] = self._date_header(self._header_value(metadata.date))
|
|
163
191
|
from_header = self._format_addresses([metadata.from_])
|
|
164
192
|
if from_header:
|
|
165
193
|
result["From"] = self._header_value(from_header)
|
|
@@ -171,6 +199,18 @@ class EmailParserClient:
|
|
|
171
199
|
if metadata.cc:
|
|
172
200
|
result["CC"] = self._header_value(self._format_addresses(metadata.cc))
|
|
173
201
|
|
|
202
|
+
@staticmethod
|
|
203
|
+
def _date_header(value: str) -> str | BaseHeader:
|
|
204
|
+
"""The date as written. The Date header class reads one that is not an RFC 5322 date
|
|
205
|
+
(Gmail's "Mon, 1 Jan 2024 at 12:00 PM", a date in another language) as no date and
|
|
206
|
+
writes an empty header, so such a date is set as unstructured text.
|
|
207
|
+
"""
|
|
208
|
+
try:
|
|
209
|
+
parsedate_to_datetime(value)
|
|
210
|
+
except ValueError:
|
|
211
|
+
return TEXT_HEADERS("Date", value)
|
|
212
|
+
return value
|
|
213
|
+
|
|
174
214
|
def _header_value(self, value: str) -> str:
|
|
175
215
|
# Parsed values come from message text, which may hold any Unicode line
|
|
176
216
|
# break (for example U+2028); a header value must be a single line.
|
|
@@ -182,11 +222,29 @@ class EmailParserClient:
|
|
|
182
222
|
name = contact.name.strip()
|
|
183
223
|
address = contact.address.strip()
|
|
184
224
|
if address:
|
|
185
|
-
addresses.append(
|
|
225
|
+
addresses.append(self._formataddr(name, address) if name else address)
|
|
186
226
|
elif name:
|
|
187
|
-
addresses.append(name)
|
|
227
|
+
addresses.append(self._quote_name(name))
|
|
188
228
|
return ", ".join(addresses)
|
|
189
229
|
|
|
230
|
+
@staticmethod
|
|
231
|
+
def _quote_name(name: str) -> str:
|
|
232
|
+
"""A name without an address, quoted as formataddr() quotes a name, so the header holds
|
|
233
|
+
one name: "Smith, John" would otherwise be two mailboxes, and "(...)" a comment.
|
|
234
|
+
"""
|
|
235
|
+
if NAME_SPECIALS.search(name):
|
|
236
|
+
return '"{}"'.format(NAME_ESCAPES.sub(r"\\\g<0>", name))
|
|
237
|
+
return name
|
|
238
|
+
|
|
239
|
+
@staticmethod
|
|
240
|
+
def _formataddr(name: str, address: str) -> str:
|
|
241
|
+
"""formataddr(), which refuses an address that is not ASCII (RFC 6532): the name is
|
|
242
|
+
written as formataddr() writes it, and the address as it is.
|
|
243
|
+
"""
|
|
244
|
+
if address.isascii():
|
|
245
|
+
return formataddr((name, address))
|
|
246
|
+
return formataddr((name, "")).removesuffix("<>") + f"<{address}>"
|
|
247
|
+
|
|
190
248
|
def _get_forwarded_metadata(self, message: Message) -> fp.ForwardMetadata:
|
|
191
249
|
body = self._get_body(message)
|
|
192
250
|
subject = self._header(message, "Subject")
|
|
@@ -230,7 +288,7 @@ class EmailParserClient:
|
|
|
230
288
|
if content_type == "application/octet-stream":
|
|
231
289
|
file_name = part.get_filename()
|
|
232
290
|
if file_name and file_name.lower().endswith(".eml"):
|
|
233
|
-
payload =
|
|
291
|
+
payload = self._decoded_payload(part)
|
|
234
292
|
if isinstance(payload, bytes):
|
|
235
293
|
return self._decode_bytes(payload, part.get_content_charset())
|
|
236
294
|
if isinstance(payload, str):
|
|
@@ -293,7 +351,57 @@ class EmailParserClient:
|
|
|
293
351
|
contacts.append(fp.prepare_mailbox(name, address))
|
|
294
352
|
return contacts
|
|
295
353
|
|
|
354
|
+
@staticmethod
|
|
355
|
+
def _transfer_encoding(part: Message) -> str:
|
|
356
|
+
cte = part.get("content-transfer-encoding", "")
|
|
357
|
+
return str(getattr(cte, "cte", cte)).strip().lower()
|
|
358
|
+
|
|
359
|
+
@staticmethod
|
|
360
|
+
def _text_payload(part: Message) -> str | None:
|
|
361
|
+
"""The payload as parsed when it is non-ASCII text, which a message parsed from a `str`
|
|
362
|
+
holds as text; `None` otherwise.
|
|
363
|
+
|
|
364
|
+
Read as parsed: get_payload() first decodes surrogate escapes (a `str` made from bytes
|
|
365
|
+
with "surrogateescape") with the part's charset, and those stand for bytes, which the
|
|
366
|
+
email package already reads right.
|
|
367
|
+
"""
|
|
368
|
+
payload = getattr(part, "_payload", None)
|
|
369
|
+
if not isinstance(payload, str) or payload.isascii():
|
|
370
|
+
return None
|
|
371
|
+
try:
|
|
372
|
+
payload.encode("utf-8")
|
|
373
|
+
except UnicodeEncodeError:
|
|
374
|
+
return None
|
|
375
|
+
return payload
|
|
376
|
+
|
|
377
|
+
@staticmethod
|
|
378
|
+
def _utf8_payload(part: Message, text: str) -> bytes:
|
|
379
|
+
"""The payload with its transfer encoding undone, its text read as UTF-8.
|
|
380
|
+
|
|
381
|
+
`get_payload(decode=True)` first turns the non-ASCII characters of a `str` payload into
|
|
382
|
+
Latin-1 bytes and backslash-u escapes (raw-unicode-escape): "café €" read as "caf",
|
|
383
|
+
U+FFFD, a space and the six characters of the euro sign's escape.
|
|
384
|
+
"""
|
|
385
|
+
utf8 = copy.copy(part)
|
|
386
|
+
utf8.set_payload(text.encode("utf-8"))
|
|
387
|
+
# A payload of bytes decodes to bytes, whatever its transfer encoding.
|
|
388
|
+
return cast(bytes, utf8.get_payload(decode=True))
|
|
389
|
+
|
|
390
|
+
def _decoded_payload(self, part: Message) -> object:
|
|
391
|
+
"""`part.get_payload(decode=True)`, with non-ASCII text in a `str` read as UTF-8."""
|
|
392
|
+
text = self._text_payload(part)
|
|
393
|
+
return part.get_payload(decode=True) if text is None else self._utf8_payload(part, text)
|
|
394
|
+
|
|
296
395
|
def _get_part_text(self, part: Message) -> str:
|
|
396
|
+
text = self._text_payload(part)
|
|
397
|
+
if text is not None:
|
|
398
|
+
if self._transfer_encoding(part) not in TRANSFER_ENCODINGS:
|
|
399
|
+
# 8-bit text, which the `str` holds as text already.
|
|
400
|
+
return text
|
|
401
|
+
maintype = part.get_content_maintype()
|
|
402
|
+
charset = part.get_content_charset("ascii" if maintype == "text" else None)
|
|
403
|
+
return self._decode_bytes(self._utf8_payload(part, text), charset)
|
|
404
|
+
|
|
297
405
|
get_content = getattr(part, "get_content", None)
|
|
298
406
|
if callable(get_content):
|
|
299
407
|
try:
|
|
@@ -30,8 +30,18 @@ def decode_encoded_words(match: Match[str]) -> str:
|
|
|
30
30
|
return words
|
|
31
31
|
|
|
32
32
|
|
|
33
|
+
def remove_non_graphic(s: str) -> str:
|
|
34
|
+
"""Drop every character is_graphic() rejects.
|
|
35
|
+
|
|
36
|
+
Each distinct character is judged once: a body has thousands of characters but
|
|
37
|
+
rarely more than a few hundred distinct ones, and str.translate() does the rest.
|
|
38
|
+
"""
|
|
39
|
+
rejected = {ord(char): None for char in set(s) if not is_graphic(char)}
|
|
40
|
+
return s.translate(rejected) if rejected else s
|
|
41
|
+
|
|
42
|
+
|
|
33
43
|
def preprocess_string(s: str) -> str:
|
|
34
|
-
s =
|
|
44
|
+
s = remove_non_graphic(s)
|
|
35
45
|
s = s.replace("\ufeff", "")
|
|
36
46
|
# Decode encoded words in place. email.header.decode_header() on the whole
|
|
37
47
|
# text would join every line into one (so no line-anchored pattern could
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "email-forward-parser"
|
|
7
|
-
version = "0.2.
|
|
7
|
+
version = "0.2.4"
|
|
8
8
|
description = "Python Library to parse forwarded email messages"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.14"
|
|
@@ -14,6 +14,7 @@ keywords = ["email", "forwarded-email", "parser", "eml", "mime"]
|
|
|
14
14
|
classifiers = [
|
|
15
15
|
"Programming Language :: Python :: 3",
|
|
16
16
|
"Programming Language :: Python :: 3.14",
|
|
17
|
+
"Programming Language :: Python :: 3.15",
|
|
17
18
|
"License :: OSI Approved :: Apache Software License",
|
|
18
19
|
"Topic :: Communications :: Email",
|
|
19
20
|
"Topic :: Text Processing",
|
|
@@ -22,12 +23,12 @@ classifiers = [
|
|
|
22
23
|
|
|
23
24
|
[dependency-groups]
|
|
24
25
|
dev = [
|
|
25
|
-
"black>=26.
|
|
26
|
-
"isort>=9.0.
|
|
27
|
-
"mypy>=2.
|
|
28
|
-
"pytest>=9.
|
|
29
|
-
"pytest-cov>=7,<8",
|
|
30
|
-
"ruff>=0.
|
|
26
|
+
"black>=26.10.1,<27",
|
|
27
|
+
"isort>=9.0.2,<10",
|
|
28
|
+
"mypy>=2.4.1,<3",
|
|
29
|
+
"pytest>=9.2.0,<10",
|
|
30
|
+
"pytest-cov>=7.1,<8",
|
|
31
|
+
"ruff>=0.17.6,<1",
|
|
31
32
|
]
|
|
32
33
|
|
|
33
34
|
[project.urls]
|
|
@@ -36,7 +37,7 @@ Repository = "https://github.com/felipehertzer/email-forward-parser-py"
|
|
|
36
37
|
Issues = "https://github.com/felipehertzer/email-forward-parser-py/issues"
|
|
37
38
|
|
|
38
39
|
[tool.pytest.ini_options]
|
|
39
|
-
minversion = "9.
|
|
40
|
+
minversion = "9.2.0"
|
|
40
41
|
addopts = "-ra --strict-config --strict-markers --cov=emailforwardparser --cov-branch --cov-report=term-missing --cov-fail-under=100"
|
|
41
42
|
testpaths = ["tests"]
|
|
42
43
|
xfail_strict = true
|
|
@@ -51,7 +52,7 @@ show_missing = true
|
|
|
51
52
|
|
|
52
53
|
[tool.black]
|
|
53
54
|
line-length = 100
|
|
54
|
-
target-version = ["py314"]
|
|
55
|
+
target-version = ["py314", "py315"]
|
|
55
56
|
|
|
56
57
|
[tool.isort]
|
|
57
58
|
combine_as_imports = true
|
|
@@ -406,6 +406,16 @@ def test_utils_regex_helpers_cover_empty_limited_and_duplicate_splits() -> None:
|
|
|
406
406
|
assert utils.is_graphic("\n") is True
|
|
407
407
|
|
|
408
408
|
|
|
409
|
+
def test_remove_non_graphic_keeps_text_and_whitespace_and_drops_the_rest() -> None:
|
|
410
|
+
kept = "Café 中文 🙂\n\r\t \u00a0\u2028\u2029¶€\u0301"
|
|
411
|
+
# Controls, soft hyphen, zero-width space, BOM, a lone surrogate, private use, unassigned.
|
|
412
|
+
dropped = "\x00\x07\x1b\x7f\x85\u00ad\u200b\ufeff\ud800\ue000\U000f0000\U0010ffff"
|
|
413
|
+
|
|
414
|
+
assert utils.remove_non_graphic(kept) is kept
|
|
415
|
+
assert utils.remove_non_graphic(dropped + kept[:6] + dropped + kept[6:] + dropped) == kept
|
|
416
|
+
assert utils.remove_non_graphic(dropped) == ""
|
|
417
|
+
|
|
418
|
+
|
|
409
419
|
def test_parser_unusual_empty_match_paths() -> None:
|
|
410
420
|
with patch(
|
|
411
421
|
"emailforwardparser.forward_parser.parse_mailbox",
|
|
@@ -4,6 +4,8 @@ import base64
|
|
|
4
4
|
import re
|
|
5
5
|
import time
|
|
6
6
|
from collections.abc import Callable
|
|
7
|
+
from email.mime.multipart import MIMEMultipart
|
|
8
|
+
from email.mime.text import MIMEText
|
|
7
9
|
from functools import partial
|
|
8
10
|
|
|
9
11
|
from emailforwardparser import forward_parser as fp, loop, regexs, utils
|
|
@@ -34,6 +36,15 @@ def raw_email(
|
|
|
34
36
|
)
|
|
35
37
|
|
|
36
38
|
|
|
39
|
+
def raw_emails(body: str) -> tuple[str, str]:
|
|
40
|
+
"""A forward with this body as a single text part, and as a part of a multipart."""
|
|
41
|
+
multipart = MIMEMultipart()
|
|
42
|
+
multipart["From"] = "Forwarder <forwarder@example.com>"
|
|
43
|
+
multipart["Subject"] = "Fwd: s"
|
|
44
|
+
multipart.attach(MIMEText(body, "plain", "utf-8"))
|
|
45
|
+
return raw_email("Fwd: s", body), multipart.as_string()
|
|
46
|
+
|
|
47
|
+
|
|
37
48
|
def test_forwarded_body_ending_on_from_line_does_not_crash() -> None:
|
|
38
49
|
result = fp.get_forwarded_metadata("note\nFrom: Jane <jane@example.com>", "Fwd: x")
|
|
39
50
|
|
|
@@ -216,3 +227,83 @@ def test_a_from_whose_encoded_name_decodes_to_a_line_break_is_read_without_raisi
|
|
|
216
227
|
original = client.get_original_eml(raw)
|
|
217
228
|
assert original["Send-To"] == "jane@example.com"
|
|
218
229
|
assert original["eml"].startswith(raw.splitlines()[0])
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def test_eight_bit_text_in_a_str_is_read_as_written() -> None:
|
|
233
|
+
"""Given a `str`, the email package turned the non-ASCII text of a part into Latin-1 bytes
|
|
234
|
+
and backslash-u escapes before decoding it: "café €" read as "caf", U+FFFD and "\\u20ac"."""
|
|
235
|
+
body = f"note\n\n{GMAIL_SEPARATOR}\nFrom: Jörg <jorg@example.com>\nSubject: s\n\ncafé €\n"
|
|
236
|
+
raw = (
|
|
237
|
+
"From: Forwarder <forwarder@example.com>\nSubject: Fwd: s\nMIME-Version: 1.0\n"
|
|
238
|
+
"Content-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\n\n" + body
|
|
239
|
+
)
|
|
240
|
+
client = EmailParserClient()
|
|
241
|
+
|
|
242
|
+
metadata = client.get_original_metadata(raw)
|
|
243
|
+
assert metadata.email.body == "café €"
|
|
244
|
+
assert metadata.email.from_ == MailboxResult("Jörg", "jorg@example.com")
|
|
245
|
+
# Quoted-printable that leaves non-ASCII text in place: that text is read as UTF-8.
|
|
246
|
+
quoted = raw.replace("8bit", "quoted-printable").replace("café €", "café =E2=82=AC")
|
|
247
|
+
assert client.get_original_metadata(quoted).email.body == "café €"
|
|
248
|
+
# A part that is not text decodes with its charset, else UTF-8.
|
|
249
|
+
binary = quoted.replace("text/plain; charset=utf-8", "application/x-note")
|
|
250
|
+
assert client._get_part_text(client._parse_message(binary)).endswith("café €\n")
|
|
251
|
+
# A `str` made with surrogate escapes still reads as the bytes they stand for.
|
|
252
|
+
for cte in ("8bit", "quoted-printable"):
|
|
253
|
+
escaped = (
|
|
254
|
+
"Subject: s\nContent-Type: text/plain; charset=latin-1\n"
|
|
255
|
+
f"Content-Transfer-Encoding: {cte}\n\ncaf\udce9=20\n"
|
|
256
|
+
)
|
|
257
|
+
assert client._get_part_text(client._parse_message(escaped)).startswith("café")
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def test_eight_bit_eml_attachment_in_a_str_is_read_as_written() -> None:
|
|
261
|
+
raw = (
|
|
262
|
+
'From: F <f@example.com>\nContent-Type: multipart/mixed; boundary="b"\n\n--b\n'
|
|
263
|
+
"Content-Type: application/octet-stream\n"
|
|
264
|
+
'Content-Disposition: attachment; filename="saved.eml"\n'
|
|
265
|
+
"Content-Transfer-Encoding: 8bit\n\nSubject: Café\n\nBody é\n--b--\n"
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
assert EmailParserClient().get_original_eml(raw)["eml"] == "Subject: Café\n\nBody é"
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def test_rebuilt_email_keeps_a_date_that_is_not_an_rfc_5322_date() -> None:
|
|
272
|
+
"""The Date header class wrote a date it cannot read, such as Gmail's, as an empty header.
|
|
273
|
+
A date that is not ASCII takes a UTF-8 header: a Date header holds no encoded word."""
|
|
274
|
+
client = EmailParserClient()
|
|
275
|
+
for date, written in [
|
|
276
|
+
("Mon, 1 Jan 2024 at 12:00 PM", "Mon, 1 Jan 2024 at 12:00 PM"),
|
|
277
|
+
("26. října 2021 14:25:08 GMT+3", "26. října 2021 14:25:08 GMT+3"),
|
|
278
|
+
("Mon, 1 Jan 2024 12:00:00 +0000", "Mon, 01 Jan 2024 12:00:00 +0000"),
|
|
279
|
+
]:
|
|
280
|
+
body = (
|
|
281
|
+
f"hi\n\n{GMAIL_SEPARATOR}\nFrom: Jane <jane@example.com>\nDate: {date}\n"
|
|
282
|
+
"Subject: s\n\nbody\n"
|
|
283
|
+
)
|
|
284
|
+
for raw in raw_emails(body):
|
|
285
|
+
eml = client.get_original_eml(raw)["eml"]
|
|
286
|
+
assert f"Date: {written}\n" in eml
|
|
287
|
+
assert client.get_original_metadata(eml).email.date == written
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def test_rebuilt_email_writes_headers_that_cannot_be_encoded_words() -> None:
|
|
291
|
+
"""formataddr() raised on an address that is not ASCII (RFC 6532), and the default policy
|
|
292
|
+
refused to write one, or a name without an address that is not ASCII (HeaderWriteError).
|
|
293
|
+
A name without an address with a comma in it read back as two mailboxes."""
|
|
294
|
+
body = (
|
|
295
|
+
f"hi\n\n{GMAIL_SEPARATOR}\nFrom: Jörg <jörg@exämple.com>\nSubject: s\n"
|
|
296
|
+
"To: bob@exämple.com\nCc: Müller, Hans\n\nbody\n"
|
|
297
|
+
)
|
|
298
|
+
client = EmailParserClient()
|
|
299
|
+
for raw in raw_emails(body):
|
|
300
|
+
eml = client.get_original_eml(raw)["eml"]
|
|
301
|
+
original = client.get_original_metadata(eml).email
|
|
302
|
+
|
|
303
|
+
assert 'CC: "Müller, Hans"\n' in eml
|
|
304
|
+
assert original.from_ == MailboxResult("Jörg", "jörg@exämple.com")
|
|
305
|
+
assert original.to == [MailboxResult("", "bob@exämple.com")]
|
|
306
|
+
assert original.cc == [MailboxResult("Müller, Hans", "")]
|
|
307
|
+
assert client._format_addresses([MailboxResult('Say "hi" \\ (x)', "")]) == (
|
|
308
|
+
'"Say \\"hi\\" \\\\ (x)"'
|
|
309
|
+
)
|