Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python EmailMessage: keep received newlines out of a header field

Last updated: 1 Oct 20265 min read
tutorial
IntermediateBy AITrove Editorial

A message header is a field value, not a place to concatenate received mail syntax.

Download Python source kit

Operation contract

The fixture tries to assign a received subject containing a newline and a second header name. EmailMessage rejects that assignment. It then sets a plain owned subject and body and serializes the message locally; nothing is sent.

Failure boundary

Header validation is one part of mail handling. Addresses, recipients, attachment types, message size, SMTP transport, and delivery rules need separate policies. The body of a message is not made trusted merely because its subject was accepted.

Working program

python
from email import policy
from email.message import EmailMessage

message = EmailMessage(policy=policy.SMTP)
try:
    message["Subject"] = "Receipt R-47 paid\nBcc: hidden"
except ValueError:
    print("newline_rejected", True)
message["Subject"] = "Receipt R-47 paid"
message.set_content("Receipt R-47 was recorded.")
serialized = message.as_bytes()
print("one_subject", serialized.count(b"Subject:") == 1)
print("body_present", b"Receipt R-47 was recorded." in serialized)

Output

Output
newline_rejected True
one_subject True
body_present True

Costs and limits

Serialization allocates bytes proportional to the message body. This fixture keeps one short local message and makes no mail-delivery or attachment-budget claim.

Common Mistakes

  • Do not concatenate a received value into raw header lines.
  • A valid subject does not validate a recipient or body.
  • Building bytes locally is not evidence that a message was delivered.

Connected lessons

Test this contract.

python
email-header-assembly
Storage details