Skip to content

email.policy.default adds an extra newline char to email address headers and raises HeaderWriteError on stringify #142006

@fumiyas

Description

@fumiyas

Bug report

Bug description:

Reproducer script:

#!/usr/bin/env python3

import email
import email.policy

msg_bytes = b"""\
To: loooooooooooooooooooooooooooooooooooong@dooooooooooooomainname.example.com,
 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.example.com

body
"""

msg = email.message_from_bytes(msg_bytes, policy=email.policy.default)
print(msg['to'])
print(msg)

Output:

$ python3.14 test.py
loooooooooooooooooooooooooooooooooooong@dooooooooooooomainname.example.com, xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.example.com
Traceback (most recent call last):
  File "/home/fumiyas/test.py", line 15, in <module>
    print(msg)
    ~~~~~^^^^^
  File "/usr/lib/python3.14/email/message.py", line 1009, in __str__
    return self.as_string(policy=self.policy.clone(utf8=True))
           ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.14/email/message.py", line 1006, in as_string
    return super().as_string(unixfrom, maxheaderlen, policy)
           ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.14/email/message.py", line 188, in as_string
    g.flatten(self, unixfrom=unixfrom)
    ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.14/email/generator.py", line 117, in flatten
    self._write(msg)
    ~~~~~~~~~~~^^^^^
  File "/usr/lib/python3.14/email/generator.py", line 200, in _write
    self._write_headers(msg)
    ~~~~~~~~~~~~~~~~~~~^^^^^
  File "/usr/lib/python3.14/email/generator.py", line 234, in _write_headers
    raise HeaderWriteError(
        f'folded header contains newline: {folded!r}')
email.errors.HeaderWriteError: folded header contains newline: 'To: loooooooooooooooooooooooooooooooooooong@dooooooooooooomainname.example.com,\n\n xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.example.com\n'

No problem with email.policy.compat32.

CPython versions tested on:

3.13, 3.14, 3.12, 3.11, 3.10, 3.9

Operating systems tested on:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytopic-emailtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions