Skip to content

asEmailMessage() raises ValueError when message has multiple TO recipients #476

@glorat

Description

@glorat

Bug Metadata

  • Version of extract_msg: 0.55.0
  • Your python version: Python 3.12
  • How did you launch extract_msg?
    • My command line or
    • I used the extract_msg package

Describe the bug
Calling asEmailMessage() on a .msg file with multiple To recipients raises a ValueError from Python's email library. The root cause is that
msg.header (an email.message.Message) allows repeated keys, so a multi-recipient message produces two separate TO entries. The header-copying loop
assigns each one individually via ret[key] = value, but EmailMessage.__setitem__ enforces a maximum of one TO field.

What code did you use or can we use to reproduce this error?

import extract_msg

with extract_msg.openMsg("multi-to.msg") as msg:                                                                                                              
    em = msg.asEmailMessage()

Is there a message.msg file you want to share to help us reproduce this?

  • Uploaded message (drag and drop on this window)

Traceback

File ".../extract_msg/msg_classes/message_base.py", line 171, in asEmailMessage
    ret[key] = value.replace('\r\n', '').replace('\n', '')
  File ".../email/message.py", line 439, in __setitem__                                                                                                       
    raise ValueError("There may be at most {} {} headers "
ValueError: There may be at most 1 TO headers in a message                                                                                                    

Additional context
The offending loop is in message_base.py around line 169:

for key, value in self.header.items():
    if key.lower() != 'content-type':
        ret[key] = value.replace('\r\n', '').replace('\n', '')

When there are multiple TO entries, the second assignment raises. The fix is to merge duplicate header values with a comma before assigning, which produces
valid RFC 5322 output (TO: alice@example.com, carol@example.com). A PR with the fix is forthcoming.

multi-to.msg

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions