Skip to content

fix(email): handle UnicodeDecodeError for .msg files with 8-bit body - #5439

Merged
DanielNg0729 merged 6 commits into
docling-project:mainfrom
todkarsant:fix/msg-8bit-body-decode-5414
Nov 22, 2026
Merged

DanielNg0729 merged 6 commits into
docling-project:mainfrom
todkarsant:fix/msg-8bit-body-decode-5414

Conversation

@todkarsant

Copy link
Copy Markdown
Contributor

Fixes #5414

What

Catch UnicodeDecodeError on message.body and message.html_body in _msg_to_rfc822_bytes so the backend loads and extracts metadata (subject, recipients, date, attachments) instead of raising DocumentLoadError.

Why

python-oxmsg <=0.0.2 decodes 8-bit (non-Unicode) body properties with the internet code page instead of the message code page, raising UnicodeDecodeError when the two differ (e.g. internet=UTF-8, message=cp1252). The upstream fix is pending (python-oxmsg#5, python-oxmsg#6) with no maintainer activity since Feb 2025.

Changes

  • email_backend.py: wrap message.body and message.html_body with UnicodeDecodeError handling and log a warning
  • test_backend_email.py: add test_msg_loads_when_body_raises_unicode_decode_error that patches OxMsgMessage.body to raise and verifies the backend still initialises, converts, and produces metadata

python-oxmsg <=0.0.2 decodes 8-bit (non-Unicode) body properties with
the internet code page instead of the message code page, raising
UnicodeDecodeError when the two differ (e.g. internet=UTF-8,
message=cp1252).

Catch UnicodeDecodeError on message.body and message.html_body so the
backend still loads and extracts metadata (subject, recipients, date,
attachments) rather than failing with DocumentLoadError.

Fixes docling-project#5414
@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

✅ DCO Check Passed

Thanks @todkarsant, all your commits are properly signed off. 🎉

@mergify

mergify Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Merge Protections

🟢 Merge protection satisfied — ready to merge.

Show 1 satisfied protection

🟢 Enforce conventional commit

Make sure that we follow https://www.conventionalcommits.org/en/v1.0.0/

  • title ~= ^(fix|feat|docs|style|refactor|perf|test|build|ci|chore|revert)(?:\(.+\))?(!)?:

@github-actions github-actions Bot added ai:ci-safe AI triage found no CI-safety concern (advisory) bug Something isn't working email issue related to email (EML, MSG) backend priority:medium labels Nov 17, 2026
@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

AI triage (advisory)

Checked commit 50c2dd28d7. The analysis read the diff only. It did not run code from this pull request.

This pull request catches decode and lookup errors when loading .msg email files. It recovers plain-text bodies from the OLE stream and logs warnings for unreadable properties.

CI safety: no concern found. A maintainer must still approve CI.

2 related pull request(s) in the same code
PR State Signal Assessment
#5420 open changes the same code related: Candidate 5420 preserves sender display names for Exchange senders in .msg files.
#5425 open changes the same code related: Candidate 5425 filters inline and hidden Outlook attachments in .msg files.

The ai:* labels are advisory. They do not approve CI and they do not add tests:full. A new push runs this check again.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI first review (advisory): no blocker found

This review covers the full diff at 10182711dc. It read the code and did not run it.

The change catches UnicodeDecodeError only on message.body and message.html_body. The body text is dropped and the converted document has no content. The fix may not cover the other 8-bit properties, and the test does not use a real file.

A maintainer makes the merge decision. This review never approves the pull request.

Comment thread docling/backend/email_backend.py Resolved
@github-actions github-actions Bot added the ai:review-lgtm AI first review found no blocker or major issue (advisory) label Nov 17, 2026
@codecov

codecov Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 59.25926% with 22 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
docling/backend/email_backend.py 59.25% 19 Missing and 3 partials ⚠️

📢 Thoughts on this report? Let us know!

…com>

I, Santosh Todkar <[email protected]>, hereby add my Signed-off-by to this commit: 1018271

Signed-off-by: Santosh Todkar <[email protected]>
@github-actions github-actions Bot removed ai:ci-safe AI triage found no CI-safety concern (advisory) ai:review-lgtm AI first review found no blocker or major issue (advisory) labels Nov 17, 2026
…com>

I, Santosh Todkar <[email protected]>, hereby add my Signed-off-by to this commit: 1018271

Signed-off-by: Santosh Todkar <[email protected]>
@github-actions github-actions Bot added the ai:ci-safe AI triage found no CI-safety concern (advisory) label Nov 17, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI first review (advisory): no blocker found

This review covers the changes since 10182711dc at 94a82b9d63. It read the code and did not run it.

There are no new changes since the earlier review. The open question about potential decode failures on other 8-bit properties remains unaddressed.

Earlier findings

  • open (question): Same decode failure may still occur on other 8-bit properties; test uses a mock, not a real file

A maintainer makes the merge decision. This review never approves the pull request.

@github-actions github-actions Bot added the ai:review-lgtm AI first review found no blocker or major issue (advisory) label Nov 17, 2026

@SoulmatelynchVFX SoulmatelynchVFX left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two notes on where the guard sits, from reading python-oxmsg 0.0.2 alongside this function.

The two try blocks catch exceptions from two different decoders. In oxmsg/properties.py (String8Property.value) the codec is picked per property id: self._body_encoding if self.pid == c.PID_BODY else self._str_prop_encoding. body_encoding comes from PID_INTERNET_CODEPAGE, _str_prop_encoding from PID_MESSAGE_CODEPAGE with an iso-8859-15 fallback. So message.body is the only attribute that can fail on the internet code page; message.html_body's str_prop_value(PID_BODY_HTML) branch already decodes with the message code page, not the internet one.

That split means a UnicodeDecodeError can arrive before either block: message.subject (email_backend.py:266) and message.sender (:270) use the message code page, as do the recipient rows (:276) and attachment.file_name (:327). When PID_MESSAGE_CODEPAGE is absent the fallback is iso-8859-15, a single-byte codec, so those cannot raise. When it is present and names a multi-byte codec they can: encoding_from_codepage(936) is gb2312, and b"caf\xe9".decode("gb2312") raises incomplete multibyte sequence (932 and 950 behave the same). PID_MESSAGE_CODEPAGE is exactly what CJK Outlook mail carries, so those files still end in DocumentLoadError after this patch.

I did not verify which of these properties real clients leave as PtypString8; the repo's own msg_simple.msg stores the body as PtypString UTF-16, so the new branch is only reachable through the mock. If the goal is "a .msg with a bad 8-bit property still loads", the header assembly at :266-:276 needs the same treatment; if the goal is bodies only, the comment could say so, since the current wording reads as the general case.

AI assistance: drafted with an AI assistant reading the diff and the oxmsg source; only the codec checks above were executed, not a real .msg.

Extend the UnicodeDecodeError guards to subject, sender, recipients,
and attachment filenames — not just body and html_body. When
PID_MESSAGE_CODEPAGE names a multi-byte codec (gb2312, Shift-JIS,
Big5), any PtypString8 property can fail. The backend now loads
whatever it can decode rather than raising DocumentLoadError.

Add tests for the html_body and subject failure paths. The body test
now also asserts the body text is lost (visible effect for users).

Signed-off-by: Santosh Todkar <[email protected]>
@github-actions github-actions Bot removed the ai:ci-safe AI triage found no CI-safety concern (advisory) label Nov 18, 2026
@todkarsant

Copy link
Copy Markdown
Contributor Author

Thanks @SoulmatelynchVFX for the thorough review — the CJK multi-byte codec point is spot-on.

Pushed a follow-up commit that:

  • Guards message.subject, message.sender, recipient name/email, and attachment.file_name against UnicodeDecodeError — same treatment as the body properties.
  • Adds tests for the html_body and subject failure paths.
  • The body test now also asserts the body text is actually lost (visible user effect), as the automated review suggested.
  • Updated the docstring to document the full scope of the guards and the two failure modes (wrong codepage for body, multi-byte codec for any PtypString8 property).

No real 8-bit .msg fixture is available (the reporter's files are internal), so the tests use mocks. This limit is noted in the test docstrings.

@github-actions github-actions Bot added ai:ci-safe AI triage found no CI-safety concern (advisory) and removed ai:review-lgtm AI first review found no blocker or major issue (advisory) labels Nov 18, 2026

@DanielNg0729 DanielNg0729 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @todkarsant, thank you for picking up #5414! I tried the PR on a .msg that reproduces the issue. I built it from msg_simple.msg: the body is stored as 8-bit cp1252 text with é, the internet code page is 65001 and the message code page is 1252, so message.body raises the same UnicodeDecodeError as in the issue. Two things came up:

  1. The body is dropped, but the result reports success. On main the file fails with "Could not initialize email backend". With this PR it gives ConversionStatus.SUCCESS and errors=[], but the Markdown has only the subject, From, To and Date. The email text is gone, and only a log warning says so. The reporter mentioned that decoding the same bytes as cp1252 gives the right text. Would it make sense to recover the body that way when the default decode fails? Roughly (olefile is already a dependency of python-oxmsg):

    codepage = message.properties.int_prop_value(c.PID_MESSAGE_CODEPAGE)
    with olefile.OleFileIO(data) as ole:
        raw = ole.openstream(f"__substg1.0_{c.PID_BODY:04X}{c.PTYP_STRING8:04X}").read()
    plain_body = raw.decode(encoding_from_codepage(codepage), errors="replace")

    On the test file this gives "Café crème at the résumé meeting.", and dropping the body could stay as the last resort.

  2. Code pages 874 and 950 raise LookupError, not UnicodeDecodeError. python-oxmsg maps them to windows-874 and windows-950, which Python does not know (codecs.lookup("windows-950") raises). So every 8-bit property of a Thai or Traditional Chinese message fails before a single byte is decoded, even a pure-ASCII subject. I set the message code page to 950 on the same test file with an 8-bit subject, and it still fails with "Could not initialize email backend" on this PR. Would it make sense to catch LookupError too?

…n codecs

Address review from @DanielNg0729:

1. When message.body fails, recover the body by reading raw bytes from
   the OLE compound file and decoding with the message code page. The
   body is no longer silently dropped — olefile (already a transitive
   dependency) reads the PtypString8 stream directly.

2. Catch LookupError alongside UnicodeDecodeError on every guarded
   property. python-oxmsg maps code page 950 to 'windows-950', which
   Python does not recognise — this raises LookupError, not
   UnicodeDecodeError, so Thai and Traditional Chinese .msg files
   failed before this fix.

Signed-off-by: Santosh Todkar <[email protected]>
@github-actions github-actions Bot removed the ai:ci-safe AI triage found no CI-safety concern (advisory) label Nov 18, 2026
@todkarsant

Copy link
Copy Markdown
Contributor Author

Thanks @DanielNg0729 for testing with a real .msg file — both findings are spot-on. Pushed a fix addressing both:

1. Body recovery via OLE stream
When message.body fails, the backend now reads the raw PtypString8 bytes from the OLE compound file via olefile (already a transitive dependency of python-oxmsg) and decodes them with the message code page:

codepage = message.properties.int_prop_value(0x3FFD)  # PID_MESSAGE_CODEPAGE
encoding = encoding_from_codepage(codepage)
stream = f"__substg1.0_{PID_BODY:04X}{PTYP_STRING8:04X}"
raw = ole.openstream(stream).read()
plain_body = raw.decode(encoding, errors="replace")

For the test file you described (cp1252 body with é), this would produce "Café crème at the résumé meeting." instead of dropping the body.

2. LookupError caught everywhere
All guarded properties now catch (UnicodeDecodeError, LookupError). Confirmed that codecs.lookup("windows-950") raises LookupError on Python 3.12+, so Traditional Chinese and Thai .msg files were still crashing. Test added with LookupError on subject.

@github-actions github-actions Bot added the ai:ci-safe AI triage found no CI-safety concern (advisory) label Nov 18, 2026
@DanielNg0729

Copy link
Copy Markdown
Member

Thanks for the quick fix @todkarsant, can you resolve the lint and type failure first before we continue to review again. Thank you

@github-actions github-actions Bot removed the ai:ci-safe AI triage found no CI-safety concern (advisory) label Nov 18, 2026
@todkarsant

Copy link
Copy Markdown
Contributor Author

@DanielNg0729 Fixed — removed the quoted type annotation (ruff UP037). CI should be green now.

@todkarsant

Copy link
Copy Markdown
Contributor Author

@DanielNg0729 lint is resolved and CI is green — ready for re-review whenever you get a chance. Thanks!

@DanielNg0729 DanielNg0729 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm!

@todkarsant

Copy link
Copy Markdown
Contributor Author

@DanielNg0729 Thanks for the approval! Is there anything else needed from my side before this can be merged?

1 similar comment
@todkarsant

Copy link
Copy Markdown
Contributor Author

@DanielNg0729 Thanks for the approval! Is there anything else needed from my side before this can be merged?

@DanielNg0729
DanielNg0729 merged commit 0f3564c into docling-project:main Nov 22, 2026
34 checks passed
DanielNg0729 added a commit to Kylinny/docling that referenced this pull request Nov 26, 2026
Resolve the conflict with docling-project#5439 in _msg_to_rfc822_bytes: keep the
UnicodeDecodeError/LookupError guard on message.sender and pass the
guarded value to _msg_sender_header. Keep both _msg_sender_header and
_recover_msg_body, and merge the two docstrings.

The docling-project#5439 tests call _msg_to_rfc822_bytes directly, so unpack the new
(bytes, sender_fallback) return value there too.

Signed-off-by: Daniel Nguyen <[email protected]>
DanielNg0729 added a commit to Kylinny/docling that referenced this pull request Nov 26, 2026
Since docling-project#5439, every python-oxmsg string read in _msg_to_rfc822_bytes
catches UnicodeDecodeError and LookupError, and the docstring says so.
The new PidTagSenderName and PidTagSenderSmtpAddress reads did not. When
they fail, log a warning and build the From header from the sender
string alone.

Signed-off-by: Daniel Nguyen <[email protected]>
dolfim-ibm pushed a commit that referenced this pull request Nov 26, 2026
* fix(email): keep display name of Exchange sender in .msg files

For .msg files sent inside an Exchange organisation, python-oxmsg
returns the sender as the display name with the legacy Exchange DN
in the angle brackets (e.g. "Display Name </O=ORG/OU=.../CN=...>"),
which is not a valid addr-spec. mailparser drops the whole mailbox,
so convert() emitted no From: line at all.

When the sender has no SMTP address, write the display name alone
into the projected From header and carry it through as a fallback so
convert() renders it. A recorded PidTagSenderSmtpAddress is preferred
when present (oxmsg's sender string shows the DN even then), and
senders with an SMTP address are passed through unchanged.

Adds a regression test with a synthetic .msg fixture whose sender is
an internal Exchange sender, plus unit tests for the sender handling.

Fixes #5415

Signed-off-by: Junyi Yao <[email protected]>

* test(email): move the .msg sender tests to their own module

After the merge with main, tests/test_backend_email.py has 1522 lines,
over the 1500-line limit of the max-lines hook. Move the five sender
tests of this PR, unchanged, to tests/test_backend_email_msg_sender.py.

Signed-off-by: Daniel Nguyen <[email protected]>

* fix(email): keep the Exchange sender name free of the DN comment

A real legacy Exchange DN holds a group in parentheses, for example
"/O=EXCHANGELABS/OU=EXCHANGE ADMINISTRATIVE GROUP (FYDIBOHF23SPDLT)/...".
getaddresses() reads that group as a comment and appends it to the
display name, so the From line showed "Doe, Jonathan (FYDIBOHF23SPDLT)".
When the sender string has angle brackets, python-oxmsg built it from
PidTagSenderName, so take the name from that property instead. This also
keeps quotes in a name such as 'Jonathan "JD" Doe'.

When no sender address is recorded, python-oxmsg returns
PidTagSentRepresentingName without quotes, e.g. "Doe, Jonathan".
getaddresses() split it on the comma, and the From line was lost. Check
for a bare name before getaddresses() runs.

Signed-off-by: Daniel Nguyen <[email protected]>

* fix(email): guard the .msg sender property reads

Since #5439, every python-oxmsg string read in _msg_to_rfc822_bytes
catches UnicodeDecodeError and LookupError, and the docstring says so.
The new PidTagSenderName and PidTagSenderSmtpAddress reads did not. When
they fail, log a warning and build the From header from the sender
string alone.

Signed-off-by: Daniel Nguyen <[email protected]>

---------

Signed-off-by: Junyi Yao <[email protected]>
Signed-off-by: Daniel Nguyen <[email protected]>
Co-authored-by: Daniel Nguyen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ai:ci-safe AI triage found no CI-safety concern (advisory) bug Something isn't working email issue related to email (EML, MSG) backend priority:medium

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Email backend fails on .msg files with 8-bit (non-Unicode) string properties

3 participants