Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
## 0.27.30

### Fixes

- **Keep non-ASCII email names and addresses readable.** `partition_email()` formatted the `sent_from`, `sent_to`, `cc_recipient` and `bcc_recipient` metadata with `email.utils.formataddr()`, which wrote a non-ASCII display name as an RFC 2047 encoded-word (`=?utf-8?b?5byg5Lyf?= <zhang@example.cn>` for 张伟) and raised `UnicodeEncodeError` on a non-ASCII address (RFC 6532), failing the whole message. Names and addresses are now kept as written; ASCII ones are formatted as before.

## 0.27.29

### Fixes
Expand Down
35 changes: 35 additions & 0 deletions test_unstructured/partition/test_email.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from __future__ import annotations

import email.policy
import io
import tempfile
from email.message import EmailMessage
Expand Down Expand Up @@ -221,6 +222,40 @@ def test_partition_email_augments_message_body_elements_with_email_metadata():
assert all(e.metadata.subject == "Example Plain-Text MIME Message" for e in elements)


def test_partition_email_keeps_non_ascii_display_names_readable():
# -- mail clients write a non-ASCII display name as an RFC 2047 encoded-word, which
# -- `email.utils.formataddr()` would produce again, e.g. "=?utf-8?b?5byg5Lyf?=" for "张伟" --
msg = EmailMessage(policy=email.policy.SMTP)
msg["From"] = "José García <jose@ejemplo.es>"
msg["To"] = "张伟 <zhang@example.cn>, Jürgen Müller <juergen@beispiel.de>"
msg["Cc"] = '"Müller, Jürgen" <j.mueller@beispiel.de>'
msg["Bcc"] = "Zoë <zoe@example.com>"
msg.set_content("Hello")

element = partition_email(file=io.BytesIO(msg.as_bytes()))[0]

assert element.metadata.sent_from == ["José García <jose@ejemplo.es>"]
assert element.metadata.sent_to == [
"张伟 <zhang@example.cn>",
"Jürgen Müller <juergen@beispiel.de>",
]
assert element.metadata.cc_recipient == ['"Müller, Jürgen" <j.mueller@beispiel.de>']
assert element.metadata.bcc_recipient == ["Zoë <zoe@example.com>"]


def test_partition_email_accepts_non_ascii_addresses():
# -- RFC 6532 allows UTF-8 in addresses; `email.utils.formataddr()` raises on them --
msg = EmailMessage(policy=email.policy.SMTPUTF8)
msg["From"] = "José <josé@ejemplo.es>"
msg["To"] = "Jürgen <jürgen@beispiel.de>, alice@example.com"
msg.set_content("Hello")

element = partition_email(file=io.BytesIO(msg.as_bytes()))[0]

assert element.metadata.sent_from == ["José <josé@ejemplo.es>"]
assert element.metadata.sent_to == ["Jürgen <jürgen@beispiel.de>", "alice@example.com"]


# -- .metadata.filename --------------------------------------------------------------------------


Expand Down
2 changes: 1 addition & 1 deletion unstructured/__version__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.27.29" # pragma: no cover
__version__ = "0.27.30" # pragma: no cover
28 changes: 24 additions & 4 deletions unstructured/partition/email.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import email.utils
import io
import os
import re
from email.message import EmailMessage, MIMEPart
from functools import cached_property
from typing import IO, Any, Final, Iterator, cast
Expand All @@ -32,6 +33,25 @@

VALID_CONTENT_SOURCES: Final[tuple[str, ...]] = ("text/html", "text/plain")

# -- the characters for which `email.utils.formataddr()` quotes a display name, and those it then
# -- escapes with a backslash --
_SPECIALS_RE: Final[re.Pattern[str]] = re.compile(r'[][\\()<>@,:;".]')
_ESCAPES_RE: Final[re.Pattern[str]] = re.compile(r'[\\"]')


def _format_address(name: str, address: str) -> str:
"""Format `name` and `address` like `email.utils.formataddr()`, leaving non-ASCII text as is.

`formataddr()` writes a non-ASCII display name as an RFC 2047 encoded-word, e.g.
"=?utf-8?b?5byg5Lyf?=" for "张伟", and raises `UnicodeEncodeError` on a non-ASCII address,
which RFC 6532 allows. ASCII names and addresses get the same result as `formataddr()`.
"""
if not name:
return address
quotes = '"' if _SPECIALS_RE.search(name) else ""
name = _ESCAPES_RE.sub(r"\\\g<0>", name)
return f"{quotes}{name}{quotes} <{address}>"


@partition_runtime_telemetry("eml")
def partition_email(
Expand Down Expand Up @@ -132,7 +152,7 @@ def bcc_addresses(self) -> list[str] | None:
if not bccs:
return None
addrs = email.utils.getaddresses(bccs)
return [email.utils.formataddr(addr) for addr in addrs]
return [_format_address(*addr) for addr in addrs]

@cached_property
def body_part(self) -> MIMEPart | None:
Expand All @@ -150,7 +170,7 @@ def cc_addresses(self) -> list[str] | None:
if not ccs:
return None
addrs = email.utils.getaddresses(ccs)
return [email.utils.formataddr(addr) for addr in addrs]
return [_format_address(*addr) for addr in addrs]

@cached_property
def content_type_preference(self) -> tuple[str, ...]:
Expand Down Expand Up @@ -185,7 +205,7 @@ def from_address(self) -> str | None:
# -- this should never occur because the From: header is mandatory per RFC 5322 --
return None
addrs = email.utils.getaddresses(froms)
formatted_addrs = [email.utils.formataddr(addr) for addr in addrs]
formatted_addrs = [_format_address(*addr) for addr in addrs]
return formatted_addrs[0]

@cached_property
Expand Down Expand Up @@ -275,7 +295,7 @@ def to_addresses(self) -> list[str] | None:
if not tos:
return None
addrs = email.utils.getaddresses(tos)
return [email.utils.formataddr(addr) for addr in addrs]
return [_format_address(*addr) for addr in addrs]

@cached_property
def _filesystem_last_modified(self) -> str | None:
Expand Down
Loading