Python raises ValueError: Header values may not contain linefeed or carriage return characters when a string assigned to an EmailMessage header contains any line break. When an LLM writes your subject, the usual culprit is the model appending its sign-off to the subject field. Fix: keep only the first non-empty line, at generation and again at message build.
We hit this on the very first live test send of an LLM-driven outreach pipeline running Claude Haiku 4.5 through OpenRouter, with structured output via instructor, on Python 3.12 EmailMessage + smtplib. Below: the real traceback, why the model did it, the fix we shipped, and the edge case our first fix still had.
What did the traceback actually look like?
The crash happened inside build_message() on the line msg["Subject"] = subject, before any SMTP connection was opened. The generated subject was 'quick question about your production workflow\n\nNiro': a perfectly good subject line, then a blank line, then the sender's sign-off. The model had put its signature into the subject field.
Here is the log, with the recipient address and the server path redacted:
2026-04-02 16:44:29 INFO TEST MODE: Subject: quick question about your production workflow
Niro
2026-04-02 16:44:29 ERROR TEST MODE: SMTP failure — email not sent.
Traceback (most recent call last):
File "/app/sender.py", line 158, in run_test
msg = build_message(to_addr=destination, subject=subject, body=body)
File "/app/sender.py", line 84, in build_message
msg["Subject"] = subject
~~~^^^^^^^^^^^
File "/usr/lib/python3.12/email/message.py", line 437, in __setitem__
self._headers.append(self.policy.header_store_parse(name, val))
File "/usr/lib/python3.12/email/policy.py", line 146, in header_store_parse
raise ValueError("Header values may not contain linefeed "
ValueError: Header values may not contain linefeed or carriage return characters
Notice the log line itself is split across three lines. That was the first hint: our logger printed the subject verbatim, and the subject was not one line.
Why did the LLM put a newline in the subject?
Because the system prompt told it to end the email with "Blank line, then just: Niro", and the response schema gave it two free-text string fields with no constraint on either. In JSON mode the model applied the sign-off instruction to the subject as well as the body. Nothing stopped it from reaching the header.
The response model was about as minimal as it gets:
class EmailDraft(BaseModel):
subject: str
body: str
Pydantic validated it happily, because '...workflow\n\nNiro' is a valid str. We ran generation at temperature 0.8 for variety, which makes the failure intermittent rather than constant. The next draft in the queue carried the same \n\nNiro tail on a completely different subject. A schema that says "string" is a promise about type, not about shape, and an email header has a strict shape.
We cover the broader class of "the structured output parsed, but the content is wrong" in what 97 failed LLM JSON calls across 65 production runs actually looked like.
Why does Python reject the header instead of folding it?
An email header is one logical line. Under RFC 5322 a header ends at CRLF, and a blank line ends the whole header block. So a raw newline inside a value is header injection, not formatting. The modern email.policy API refuses it outright when you assign the header, instead of guessing what you meant.
The check lives in EmailPolicy.header_store_parse, which the Python email.policy documentation describes as raising ValueError if the input value contains CR or LF characters. The implementation is broader than the message suggests, though. It uses len(value.splitlines()) > 1, and a source comment admits the error text "isn't quite right".
We tested what actually trips it on Python 3.12.3:
LF '\n' ValueError
CR '\r' ValueError
VT '\x0b' ValueError
NEL '\x85' ValueError
U+2028 '
' ValueError
That matters for LLM output specifically. Unicode line separators can show up in model output, especially when the model echoes scraped profile text, and you will get an error message about "linefeed or carriage return" for a string that contains neither. If you sanitize with .replace("\n", " "), you have fixed the one character the error names and missed the others.
What is the fix we shipped?
We added two layers: a sanitizer on the generator output, and a guard at message-build time that keeps only the first line of the stripped subject. The generator layer keeps bad subjects out of the queue. The build layer protects anything already stored there, and any future code path that skips the generator.
At generation time (pipeline/generator.py), applied to every draft before it is written to the queue database:
def _sanitize_subject(text: str) -> str:
"""Clean subject line: single line, no dashes, no signature."""
text = text.replace("—", "-").replace("–", "-")
return text.strip().splitlines()[0]
At build time (sender.py):
def build_message(to_addr: str, subject: str, body: str) -> EmailMessage:
msg = EmailMessage()
msg["From"] = FROM_ADDR
msg["To"] = to_addr
msg["Subject"] = subject.strip().splitlines()[0]
msg["Date"] = formatdate(localtime=False)
msg["Message-ID"] = make_msgid(domain="example.com")
msg.set_content(body)
return msg
The build-time guard paid off immediately. Drafts generated before the sanitizer existed were still sitting in the queue with \n\nNiro tails, and our log shows them logged with the multi-line subject and then SUCCESS, because build_message trimmed them on the way out. After regenerating, all 82 queued drafts had single-line subjects.
Because splitlines() splits on exactly the same set of characters the policy check uses, splitlines()[0] is guaranteed to pass header_store_parse. That symmetry is why we used it instead of a regex on \r\n.
What edge case does splitlines()[0] still miss?
Two of them. If the model returns an empty or whitespace-only subject, "".strip().splitlines()[0] raises IndexError: list index out of range, so you swap one crash for another. And if the model leads with the sign-off, as in "Niro\nreal subject", the first line is the signature, so your email goes out with the subject "Niro".
This is the hardened version we would ship today. We ran it against every failure shape we have seen:
import re
from pydantic import BaseModel, field_validator
SIGNOFF = re.compile(r"^(niro|best|thanks|cheers)[,.!]?$", re.I)
def sanitize_subject(raw: str, fallback: str = "quick question") -> str:
# splitlines() splits on every char the email policy rejects:
# \n \r \v \f \x1c-\x1e \x85
lines = [l.strip() for l in raw.splitlines() if l.strip()]
lines = [l for l in lines if not SIGNOFF.match(l)]
if not lines:
return fallback
return re.sub(r"\s+", " ", lines[0])[:120]
class EmailDraft(BaseModel):
subject: str
body: str
@field_validator("subject")
@classmethod
def single_line_subject(cls, v: str) -> str:
return sanitize_subject(v)
'quick question about your production workflow\n\nNiro' -> 'quick question about your production workflow'
'\n\nNiro' -> 'quick question'
'' -> 'quick question'
'Niro\nshort-form video tool' -> 'short-form video tool'
'a
b' -> 'a'
' spaced\tout ' -> 'spaced out'
Replace the SIGNOFF pattern with your own sender's name and sign-offs. Putting the sanitizer in a Pydantic validator means every EmailDraft is clean the moment it exists, including drafts created by a rewrite pass that never touches your original sanitizer. Keep the build-time guard anyway. It costs nothing.
Should the validator clean the subject or make instructor retry?
Clean it. If a validator raises, instructor re-asks the model with the validation error, which costs a full extra completion. For a multi-line subject the correct answer is almost always the first line, so a deterministic trim is cheaper, faster, and does not depend on the model obeying a second time.
We considered the re-ask route and ruled it out for throughput reasons. The pipeline generated drafts at up to 40 requests per second with max_retries=3. Turning a formatting slip into up to three additional paid calls, each at temperature 0.8 with its own chance of repeating the mistake, is the wrong trade when the fix is one line of string handling.
Re-asking is the right tool when the content is wrong: a subject that is empty, a placeholder like [First Name], or one that echoes the prompt. In those cases, raise in the validator and let the model try again. Formatting gets fixed in code. Content goes back to the model.
Is the legacy email.message.Message API a workaround?
No. Switching to the legacy email.message.Message (the compat32 policy) moves the failure; it does not remove it. On a patched Python, the assignment succeeds but serialization raises HeaderWriteError. On an unpatched one, the newline is written straight into the headers, and that is a header-injection vulnerability.
We tested it on the same Python 3.12.3 (a distro build with security backports):
m = Message()
m["Subject"] = "quick question about your production workflow\n\nNiro" # accepted
m.as_string()
# HeaderWriteError: folded header contains newline:
# 'Subject: quick question about your production workflow\nNiro\n'
That serialization check is the fix for CVE-2024-6923, where the email module did not properly quote newlines in headers. On older interpreters without it, our \n\nNiro subject would have ended the header block early. Now picture a model that has been prompt-injected through a scraped bio into writing \nBcc: someone@example.com. The ValueError is protecting you. Don't route around it.
Which other LLM-generated fields break headers in 2026?
Any field that ends up in a single-line protocol slot has the same bug: the sender display name in From, Reply-To, attachment filenames in Content-Disposition, HTTP header values, and log lines. Now that teams wire structured LLM output into real protocols, sanitize per destination, not per model call.
The pattern we now follow on every LLM-to-protocol boundary:
- Constrain in the schema where you can: a
field_validatorthat normalizes shape (single line, length cap, no placeholders). - Guard at the sink: the code that writes the header, filename, or log line enforces its own invariant, whatever the upstream claims.
- Log with
repr()for model output, so a stray\nshows up as two characters in one log line instead of silently splitting your log, as it did in our traceback above. - Don't put format instructions next to free-text fields without saying which field they apply to. "End with a blank line and your name" needed to say "in the body".
The same project taught us a lot about the body text too. We wrote that up separately in why AI-generated outreach sounds like a bot, and how we fixed it with a sender voice profile.
What is the short version?
ValueError: Header values may not contain linefeed or carriage return characters from an LLM-written subject almost always means the model leaked a sign-off or a second line into a single-line field. Keep the first non-empty, non-signature line with splitlines(), which matches the policy check exactly, and fall back on empty input. Do it in a Pydantic validator and again at the point where you build the message. Never work around it with the legacy API: that error is the only thing between your model's output and header injection.