Email header injection is one of the oldest ways to turn a harmless website form into a spam relay. The idea is simple: an attacker types text containing line breaks into a field that your code places into an email header, and the extra lines become new headers such as Bcc or Cc, or even a different body. Your server then sends mail to the attacker's list using your domain, your IP and your reputation. The vulnerability appears in homemade contact forms, old mail scripts and any code that builds raw message text by string concatenation. It is entirely preventable with a few rules, and this guide explains the mechanism, the risky fields, safe patterns, validation, testing and cleanup. It pairs with protecting signup forms, server mail scripts and email spoofing.
How the attack works
An email message consists of header lines, a blank line and the body. Each header ends with a carriage return and line feed. If code builds the headers as plain text, for example by appending the visitor's email address to a Reply-To: line, then an attacker can submit a value that contains a line break followed by another header:
Visitor input in the "email" field:
[email protected]%0D%0ABcc: [email protected], [email protected]
Resulting headers when concatenated without checking:
From: [email protected]
Reply-To: [email protected]
Bcc: [email protected], [email protected]With a second blank line the attacker can also replace the body, adding their own content and links. The script sends one message per submission, and bots submit thousands. The result is blocklisted IPs, complaints and a damaged domain reputation, plus mail that is sent from your genuine authenticated infrastructure and therefore passes SPF and DKIM.
Which fields are at risk
| Field | Why it is risky | Safe handling |
|---|---|---|
| Visitor email (Reply-To, From) | Placed directly in headers | Validate as a single address; reject CR, LF; never use as the envelope From |
| Visitor name | Often joined with the address as "Name <addr>" | Strip control characters; encode non-ASCII properly |
| Subject | Frequently taken from a dropdown or text field | Fixed subject or a whitelist; reject control characters |
| Recipient (To) | Sometimes chosen by a hidden field or a query parameter | Never accept recipients from the client; map keys to addresses on the server |
| Custom headers | Features that echo user data into X- headers | Reject control characters; keep values short |
| Message body | Can contain anything, but cannot add headers in a structured library | Treat as text; escape for HTML if you send HTML |
| Attachment filenames | Used in Content-Disposition headers | Sanitise names; use library functions |
Prevention rules
- Use a maintained mail library that builds headers through methods and rejects or encodes line breaks, rather than string concatenation. Examples include PHPMailer, Symfony Mailer, Nodemailer, Python's email package and Java Mail. Use the library's address and header setters.
- Reject, do not just escape. If any header value contains CR (
\r) or LF (\n), including their URL-encoded forms after decoding, refuse the submission with a generic error. - Validate addresses strictly. Accept exactly one address in the visitor email field. Reject commas, semicolons and spaces unless you intentionally allow multiple recipients. Use the validator in your framework.
- Fix the envelope sender and From on the server. Send from an address on your domain and put the visitor address in Reply-To only. This also helps DMARC alignment. See DMARC alignment.
- Never accept recipients from the client. Do not put the destination in a hidden field. Use server-side configuration.
- Limit length and rate. Cap field lengths and throttle submissions per IP and per session.
- Add bot protection such as a challenge, honeypot field and token verification. See bot protection.
- Send through an authenticated relay with sending limits, so abuse is bounded and visible. See sending from scripts.
Safe versus unsafe patterns
# UNSAFE (pseudo-code): string concatenation
headers = "From: " + form.email + "\r\nReply-To: " + form.email
send(to, subject, body, headers)
# SAFER: structured API and explicit validation
if has_control_chars(form.email) or not is_single_valid_address(form.email):
reject()
msg = Message()
msg.sender = "[email protected]" # fixed
msg.recipient = CONFIG["contact_to"] # fixed, server side
msg.reply_to = form.email # set via API
msg.subject = "Website contact form" # fixed
msg.body = form.message # plain text
send(msg)The safer version does not guarantee safety by itself; it works because the library refuses to emit a header containing a raw line break, and because the recipient and sender are fixed.
Testing your own forms
Only test systems you own or are authorised to test. A simple checklist:
- Submit the form with a normal address and confirm one message arrives.
- Submit values containing an encoded newline, such as
%0D%0A, followed by a harmless header likeX-Test: injected, in each field. Inspect the received message source for the extra header. - Try a second address after a comma or semicolon in the email field and confirm that it is rejected.
- Try very long values and unusual Unicode, and confirm that errors are handled without sending.
- Check that errors do not reveal server paths, library names or configuration.
- Review your logs for the rejected attempts and make sure they do not trigger a send.
- Repeat after each framework or plugin upgrade, and include the test in your release routine.
Beyond forms: other places headers are built
Contact forms are the classic case, but the same flaw appears wherever user data reaches a header. Examples include "share this page with a friend" features, referral invitations, support ticket replies that copy the customer subject into a new message, import tools that map spreadsheet columns to header fields, and webhooks that relay third-party text into email. In each case, ask where the value ends up. If it lands in a header, treat it as hostile input: validate it, restrict its length, strip or reject control characters and prefer fixed values wherever the design allows. Features that let a visitor choose the recipient, such as send-to-a-friend, deserve extra limits: a low daily quota per visitor, a captcha, a fixed sender and a message template the visitor cannot rewrite entirely. Otherwise the feature itself becomes the relay, with no injection needed at all.
Frameworks help, but they do not remove responsibility. Check that the version in use includes header-safety checks, that wrappers around the library do not rebuild headers manually, and that any plugin or theme that sends mail uses the same safe path. A single forgotten legacy script on an old subdomain is often what attackers find first, so inventory every place your applications call a mail function and retire the ones nobody owns.
Signs that a form is being abused
- Sudden growth in outbound mail volume from your web server or relay account.
- Bounces or complaints about messages you do not recognise. See mail queue for finding stuck messages.
- Blocklist listings for your sending IP. Use the blocklist check.
- Queued messages with Bcc recipients unrelated to your business.
- Logs showing many form submissions with odd characters in the email field.
If you were abused
- Disable or rate-limit the form immediately.
- Pause the relay credential or sending account if volume is still high, then rotate the credential. See credential security.
- Clear the queue of unwanted messages.
- Patch the code using a structured library and validation.
- Check blocklists, authentication and complaint feedback. Request delisting where needed after the fix.
- Monitor for several days and set sending limits and alerts to catch recurrence early. See reputation recovery.
Header injection is a solved problem if you stop building headers by hand. Use structured APIs, fix the sender and recipient on the server and reject control characters, and a contact form becomes a safe channel instead of a spam gateway.
Send through a controlled relay Authenticated sending with limits keeps abuse visible and bounded.
References and further reading
Frequently asked questions
What is email header injection?
Inserting line breaks into form input so extra headers such as Bcc are added to an outgoing message, turning your server into a spam relay.
How do I prevent it?
Use a mail library that sets headers through methods, reject CR and LF in header values, validate a single address and fix sender and recipient on the server.
Is escaping the newline characters enough?
Rejecting input with control characters is safer than trying to escape it, and a structured library adds a second line of defence.
Can injected mail pass SPF and DKIM?
Yes, because it is sent from your genuine infrastructure, which is why it damages your reputation.
How can I test my contact form?
Submit values with encoded newlines followed by a harmless test header in each field on a system you own, and inspect the received source.