Skip to content

fix(email): keep display name of Exchange sender in .msg files - #5420

Merged
dolfim-ibm merged 5 commits into
docling-project:mainfrom
Kylinny:fix/email-msg-exchange-sender-5415
Nov 26, 2026
Merged

dolfim-ibm merged 5 commits into
docling-project:mainfrom
Kylinny:fix/email-msg-exchange-sender-5415

Conversation

@Kylinny

@Kylinny Kylinny commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Thank you @Antoine-BRETZNER for the clear report — the missing From: line for internal Exchange senders is a real gap, and the detail that python-oxmsg returns the display name with the legacy Exchange DN made the cause quick to find.

Fixes #5415

Problem

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 (Display Name </O=ORG/OU=.../CN=RECIPIENTS/CN=...>), which is not a valid addr-spec. The email backend wrote that value into the projected From header, mailparser then dropped the whole mailbox, and convert() emitted no From: line at all.

Reproducer

The reporter could not share their file, so this PR adds a synthetic fixture, tests/data/email/sources/msg_exchange_sender.msg — msg_simple.msg with only the sender rewritten (sender name Doe, Jonathan, sender address the legacy DN /O=EX/OU=HQ/CN=U1). Run from the repo root:

from pathlib import Path
from docling.backend.email_backend import EmailDocumentBackend
from docling.datamodel.base_models import InputFormat
from docling.datamodel.document import InputDocument

in_path = Path("tests/data/email/sources/msg_exchange_sender.msg")
in_doc = InputDocument(path_or_stream=in_path, format=InputFormat.EMAIL, backend=EmailDocumentBackend)
backend = EmailDocumentBackend(in_doc=in_doc, path_or_stream=in_path)
print(backend.convert().export_to_markdown())

Before (on main):

# Simple Email

To: Bob Example &lt;[email protected]&gt;

Date: 2026-05-20T10:30:00+00:00

Hello Bob,

This is a simple email body.

After (this PR):

# Simple Email

From: "Doe, Jonathan"

To: Bob Example &lt;[email protected]&gt;

Date: 2026-05-20T10:30:00+00:00

Hello Bob,

This is a simple email body.

Fix

  • _msg_sender_header() (new): splits the oxmsg sender into a From header value and a display-name fallback. A sender with an SMTP address is passed through exactly as before; a sender with no SMTP address (legacy Exchange DN in the angle brackets, or no address at all) keeps its display name instead. A recorded PidTagSenderSmtpAddress is preferred when present — oxmsg's sender string shows the DN even then, since it prefers PidTagSenderEmailAddress. Display names holding specials are quoted with the existing _quote_display_name helper, and header values go through _header_safe as before.
  • _msg_to_rfc822_bytes() now also returns the sender display name to show when the projected From header does not survive parsing. A bare display name cannot be a mailbox — mailparser only keeps mailboxes with an address — so writing the name alone into the header is not enough on its own; convert() uses the fallback when mailparser yields no sender. No address is invented: when there is no name either, the From header is omitted, as before. The one existing direct caller of this private helper (test_msg_to_rfc822_keeps_attachment_metadata_without_payload) was updated to unpack the returned tuple.
  • convert() passes the fallback to _format_addresses(); .eml input and SMTP senders keep the empty fallback, so their behaviour is unchanged.

Invariants:

  • Senders with an SMTP address are byte-identical to before (verbatim sender string, empty fallback).
  • Nothing is fabricated: the rendered From: line shows only the display name recorded in the file, never a synthesised address.
  • Recipient handling is untouched (out of scope for this issue).

Tests

  • test_msg_exchange_sender_keeps_display_name: end-to-end regression test on the new fixture, plus assertions on the projected From header and the fallback value.
  • Unit tests for _msg_sender_header: SMTP senders unchanged, an Exchange DN keeps the display name, a recorded SMTP address wins over the DN, bare sender names (oxmsg's sent-representing fallback), and multi-address senders passed through verbatim.

pytest tests/test_backend_email.py: 46 passed. One test fails both with and without this change (test_email_backend_converts_html_body_to_text_paragraphs) — a pre-existing failure on this base, unrelated to this change. make validate passes.

@mergify

mergify Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Merge Protections

🟢 All 2 merge protections satisfied — ready to merge.

Show 2 satisfied protections

🟢 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)(?:\(.+\))?(!)?:

🟢 Require two reviewer for test updates

When test data is updated, we require two reviewers

  • #approved-reviews-by >= 2

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 docling-project#5415

Signed-off-by: Junyi Yao <[email protected]>
@Kylinny
Kylinny force-pushed the fix/email-msg-exchange-sender-5415 branch from 86de8be to 65c89a8 Compare November 16, 2026 18:07
@github-actions

Copy link
Copy Markdown
Contributor

✅ DCO Check Passed

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

@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:low labels Nov 16, 2026
@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

AI triage (advisory)

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

This PR fixes the missing From line for .msg files from internal Exchange senders. For a sender without an SMTP address, it writes the display name to the From header and uses that name as a fallback when mailparser returns no sender.

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

2 related pull request(s) in the same code
PR State Signal Assessment
#5465 open changes the same code related: Both PRs change [_msg_to_rfc822_bytes()](docling/backend/email_backend.py:435). This PR fixes the From header for a sender without an SMTP address. The candidate reads the HTML body from the RTF body property and adds an option that prefers the HTML body. The two changes solve different problems, so neither makes the other unnecessary.
#5552 open changes the same code related: The candidate changes the sender value that [_msg_to_rfc822_bytes()](docling/backend/email_backend.py:435) reads, and this PR uses that value. The candidate also changes [_header_safe()](docling/backend/email_backend.py:391), which this PR calls for the From value. The candidate removes NUL characters from .msg strings. This PR fixes the Exchange sender, so the changes solve different problems.

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 added the ai:review-lgtm AI first review found no blocker or major issue (advisory) label Nov 16, 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 full diff at 65c89a81c6. It read the code and did not run it.

I found no defect in the .msg sender change. The sender split, the display-name fallback and the getaddresses and unquote handling are consistent with _quote_display_name and _format_addresses. I could not read the python-oxmsg source, because it is not installed in the workspace. The calls message.properties.str_prop_value(...) and message.sender are therefore unconfirmed. The existing code already calls recipient.properties.int_prop_value, which is a close sibling API.

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

@codecov

codecov Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.56098% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
docling/backend/email_backend.py 97.56% 0 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

PeterStaar-IBM
PeterStaar-IBM previously approved these changes 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 @Kylinny, thank you for the fix and the clear write-up! I ran the PR here: the 47 email tests pass, and the new fixture renders From: "Doe, Jonathan" where main shows no From: line. I may be missing something, but two things came up when I tried other sender strings:

  1. A real legacy DN puts "(FYDIBOHF23SPDLT)" into the name. Since Exchange 2007, and in Exchange Online, the DN usually looks like /O=EXCHANGELABS/OU=EXCHANGE ADMINISTRATIVE GROUP (FYDIBOHF23SPDLT)/CN=RECIPIENTS/CN=.... getaddresses() reads the part in parentheses as a comment and appends it to the display name:

    >>> getaddresses(['"Doe, Jonathan" </O=EXCHANGELABS/OU=EXCHANGE ADMINISTRATIVE GROUP (FYDIBOHF23SPDLT)/CN=RECIPIENTS/CN=4F5E6A7B8C9D-JDOE>'])
    [('Doe, Jonathan (FYDIBOHF23SPDLT)', '/O=EXCHANGELABS/OU=EXCHANGE ADMINISTRATIVE GROUP /CN=RECIPIENTS/CN=4F5E6A7B8C9D-JDOE')]

    So _msg_sender_header returns "Doe, Jonathan (FYDIBOHF23SPDLT)", and with a recorded SMTP address it returns "Doe, Jonathan (FYDIBOHF23SPDLT)" <[email protected]>. I see the same on Python 3.10, 3.12, 3.13 and 3.14. To check it end to end, I changed the DN in your fixture to /O=EX (FYD)/CN=U1 (same length), and the output is From: "Doe, Jonathan (FYD)". When the sender string has angle brackets, python-oxmsg built it from PidTagSenderName, which the function already reads. Would it make sense to prefer that property over the parsed name? It also keeps the quotes in a name such as Jonathan "JD" Doe, which the parse turns into Jonathan JD Doe.

  2. A bare name with a comma still loses the From: line (minor). When no sender address is recorded, python-oxmsg returns PidTagSentRepresentingName without quotes, e.g. Doe, Jonathan. getaddresses() splits that into two entries, so the multi-address branch passes it through unchanged, and mailparser drops it. The unit test uses '"Doe, Jonathan"' with quotes, so it does not catch this. Checking for a bare name before getaddresses() covers it.

Something like the suggestion below fixes both. With it, your 47 tests and the test below pass, and ruff is clean:

def test_msg_sender_header_ignores_parentheses_in_legacy_dn():
    """A real legacy DN holds "(FYDIBOHF23SPDLT)"; it must not reach the name."""
    header = EmailDocumentBackend._msg_sender_header
    dn = (
        "/O=EXCHANGELABS/OU=EXCHANGE ADMINISTRATIVE GROUP (FYDIBOHF23SPDLT)"
        "/CN=RECIPIENTS/CN=4F5E6A7B8C9D-JDOE"
    )
    sender = f'"Doe, Jonathan" <{dn}>'

    assert header(sender, "Doe, Jonathan", None) == (
        '"Doe, Jonathan"',
        '"Doe, Jonathan"',
    )
    assert header(sender, "Doe, Jonathan", "[email protected]") == (
        '"Doe, Jonathan" <[email protected]>',
        "",
    )
    # oxmsg returns PidTagSentRepresentingName unquoted.
    assert header("Doe, Jonathan", None, None) == (
        '"Doe, Jonathan"',
        '"Doe, Jonathan"',
    )

A heads-up, too: #5439 changes the same From block in _msg_to_rfc822_bytes and wraps the oxmsg string reads in except (UnicodeDecodeError, LookupError). The two PRs conflict there, so the new str_prop_value() reads for 0x0C1A and 0x5D01 may need the same guard after a rebase.

Also I think this keeps the name from PidTagSenderName when the sender string has angle brackets, and handles a bare name before getaddresses() splits it on the comma:

        if "<" not in sender and "@" not in sender:
            # oxmsg's sent-representing fallback: a bare display name, which
            # can hold a comma ("Doe, Jonathan").
            name = unquote(sender)
        else:
            parsed = getaddresses([sender])
            if len(parsed) != 1:
                return sender, ""
            name, address = parsed[0]
            if "@" in address:
                return sender, ""
            # oxmsg built this string from PidTagSenderName. getaddresses()
            # reads the "(FYDIBOHF23SPDLT)" group of a real legacy DN as a
            # comment and appends it to the name, so prefer the property.
            name = sender_name or name

Thanks again!

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]>
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]>
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]>
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]>
@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 26, 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 @Kylinny, thanks again for this fix! The PR had a conflict with #5439 and no update for a week, so I pushed a few commits to move it forward. I hope that is OK with you:

  • 5a56fdcf merges main. It keeps the UnicodeDecodeError/LookupError guard from #5439 on message.sender and passes the guarded value to _msg_sender_header. The #5439 tests call _msg_to_rfc822_bytes directly, so they now unpack (bytes, sender_fallback).
  • 5d7fabb9 moves the sender tests, unchanged, to tests/test_backend_email_msg_sender.py. After the merge, tests/test_backend_email.py had 1522 lines, over the 1500-line limit of the max-lines hook.
  • 38d190fd applies the two points from my review. When the sender string has angle brackets, the name now comes from PidTagSenderName, so a real DN no longer adds (FYDIBOHF23SPDLT) to it. A bare Doe, Jonathan now keeps its From: line.
  • 6e9a8c73 guards the PidTagSenderName and PidTagSenderSmtpAddress reads like the other .msg strings.

With the fixture DN changed to /O=EX (FYD)/CN=U1, the output is now From: "Doe, Jonathan" instead of From: "Doe, Jonathan (FYD)". All 66 email tests pass, and ruff and the max-lines check are clean. Please tell me if you would like anything changed.

Thanks! lgtm now

@github-actions github-actions Bot added the ai:ci-safe AI triage found no CI-safety concern (advisory) label Nov 26, 2026
@dolfim-ibm
dolfim-ibm merged commit 8a3c661 into docling-project:main Nov 26, 2026
34 checks passed
dolfim-ibm added a commit that referenced this pull request Nov 26, 2026
…est (#5615)

fix(tests): unpack the tuple from _msg_to_rfc822_bytes in the NUL test

The NUL test from #5552 assigns the result of
EmailDocumentBackend._msg_to_rfc822_bytes() to one name. #5420 changed
the helper to return (rfc822_bytes, sender_fallback), so the test now
passes a tuple to BytesIO and fails with a TypeError on main.

Unpack the tuple, like the other callers do.

Signed-off-by: Michele Dolfi <[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:low

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Email backend drops the sender of .msg files when it is an Exchange address (no SMTP address)

4 participants