email-forward-parser 0.2.3__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.
Files changed (26) hide show
  1. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/.github/workflows/workflow.yml +1 -1
  2. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/PKG-INFO +1 -1
  3. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/emailforwardparser/client.py +116 -8
  4. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/pyproject.toml +8 -8
  5. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/tests/regressions_test.py +91 -0
  6. email_forward_parser-0.2.4/uv.lock +506 -0
  7. email_forward_parser-0.2.3/uv.lock +0 -495
  8. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/.githooks/pre-push +0 -0
  9. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/.github/dependabot.yml +0 -0
  10. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/.github/workflows/ci.yml +0 -0
  11. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/.gitignore +0 -0
  12. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/.python-version +0 -0
  13. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/LICENSE +0 -0
  14. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/NOTICE +0 -0
  15. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/README.md +0 -0
  16. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/emailforwardparser/__init__.py +0 -0
  17. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/emailforwardparser/forward_parser.py +0 -0
  18. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/emailforwardparser/literals.py +0 -0
  19. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/emailforwardparser/loop.py +0 -0
  20. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/emailforwardparser/regexs.py +0 -0
  21. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/emailforwardparser/utils.py +0 -0
  22. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/tests/__init__.py +0 -0
  23. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/tests/client_test.py +0 -0
  24. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/tests/coverage_edges_test.py +0 -0
  25. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/tests/forward_parser_test.py +0 -0
  26. {email_forward_parser-0.2.3 → email_forward_parser-0.2.4}/tests/literals_test.py +0 -0
@@ -98,7 +98,7 @@ jobs:
98
98
  path: dist/
99
99
 
100
100
  - name: Publish release
101
- uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3.0.3
101
+ uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4
102
102
  with:
103
103
  files: dist/*
104
104
  generate_release_notes: true
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: email-forward-parser
3
- Version: 0.2.3
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
@@ -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.utils import formataddr, getaddresses
14
- from typing import TypedDict
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(formataddr((name, address)) if name else address)
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 = part.get_payload(decode=True)
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:
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "email-forward-parser"
7
- version = "0.2.3"
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"
@@ -23,12 +23,12 @@ classifiers = [
23
23
 
24
24
  [dependency-groups]
25
25
  dev = [
26
- "black>=26.3.1,<27",
27
- "isort>=9.0.1,<10",
28
- "mypy>=2.3,<3",
29
- "pytest>=9.1.1,<10",
30
- "pytest-cov>=7,<8",
31
- "ruff>=0.15,<1",
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",
32
32
  ]
33
33
 
34
34
  [project.urls]
@@ -37,7 +37,7 @@ Repository = "https://github.com/felipehertzer/email-forward-parser-py"
37
37
  Issues = "https://github.com/felipehertzer/email-forward-parser-py/issues"
38
38
 
39
39
  [tool.pytest.ini_options]
40
- minversion = "9.1.1"
40
+ minversion = "9.2.0"
41
41
  addopts = "-ra --strict-config --strict-markers --cov=emailforwardparser --cov-branch --cov-report=term-missing --cov-fail-under=100"
42
42
  testpaths = ["tests"]
43
43
  xfail_strict = true
@@ -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
+ )