Repository navigation
fix(email): handle UnicodeDecodeError for .msg files with 8-bit body - #5439
Conversation
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
|
✅ DCO Check Passed Thanks @todkarsant, all your commits are properly signed off. 🎉 |
Merge Protections🟢 Merge protection satisfied — ready to merge. Show 1 satisfied protection🟢 Enforce conventional commitMake sure that we follow https://www.conventionalcommits.org/en/v1.0.0/
|
AI triage (advisory)Checked commit This pull request catches decode and lookup errors when loading CI safety: no concern found. A maintainer must still approve CI. 2 related pull request(s) in the same code
The |
There was a problem hiding this comment.
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.
Codecov Report❌ Patch coverage is
📢 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]>
…com> I, Santosh Todkar <[email protected]>, hereby add my Signed-off-by to this commit: 1018271 Signed-off-by: Santosh Todkar <[email protected]>
There was a problem hiding this comment.
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.
SoulmatelynchVFX
left a comment
There was a problem hiding this comment.
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]>
|
Thanks @SoulmatelynchVFX for the thorough review — the CJK multi-byte codec point is spot-on. Pushed a follow-up commit that:
No real 8-bit |
DanielNg0729
left a comment
There was a problem hiding this comment.
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:
-
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.SUCCESSanderrors=[], 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.
-
Code pages 874 and 950 raise
LookupError, notUnicodeDecodeError. python-oxmsg maps them towindows-874andwindows-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 catchLookupErrortoo?
…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]>
|
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 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 2. |
|
Thanks for the quick fix @todkarsant, can you resolve the lint and type failure first before we continue to review again. Thank you |
Signed-off-by: Santosh Todkar <[email protected]>
|
@DanielNg0729 Fixed — removed the quoted type annotation (ruff UP037). CI should be green now. |
|
@DanielNg0729 lint is resolved and CI is green — ready for re-review whenever you get a chance. Thanks! |
|
@DanielNg0729 Thanks for the approval! Is there anything else needed from my side before this can be merged? |
1 similar comment
|
@DanielNg0729 Thanks for the approval! Is there anything else needed from my side before this can be merged? |
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]>
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]>
* 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]>
Fixes #5414
What
Catch
UnicodeDecodeErroronmessage.bodyandmessage.html_bodyin_msg_to_rfc822_bytesso the backend loads and extracts metadata (subject, recipients, date, attachments) instead of raisingDocumentLoadError.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
UnicodeDecodeErrorwhen 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: wrapmessage.bodyandmessage.html_bodywithUnicodeDecodeErrorhandling and log a warningtest_backend_email.py: addtest_msg_loads_when_body_raises_unicode_decode_errorthat patchesOxMsgMessage.bodyto raise and verifies the backend still initialises, converts, and produces metadata