Email Header Injection Explained

TL;DR

Email header injection happens when user input is included in email headers without sanitization. Attackers inject newlines to add additional headers like CC, BCC, or even modify the email body. This turns your contact form into a spam relay. Strip or reject newlines from all email-related inputs.

How Email Header Injection Works

Email headers are separated by newlines (CRLF), which means injecting a newline into any header field lets an attacker add arbitrary headers after it.

Vulnerable contact form
// User submits contact form with name field:
// "John\r\nBcc: spam-list@evil.com\r\n\r\nSpam content"

app.post('/contact', (req, res) => {
  const { name, email, message } = req.body;

  // VULNERABLE: name goes directly into headers
  sendMail({
    from: `${name} `,
    to: 'support@yoursite.com',
    subject: 'Contact Form',
    text: message
  });
});

// Resulting email has injected BCC header:
// From: John
// Bcc: spam-list@evil.com
// (blank line = end of headers, start of body)
// Spam content

What Attackers Can Do

  • Add BCC to send spam through your server
  • Modify the From address for phishing
  • Change the Subject line
  • Replace the entire email body
  • Turn your server into a spam relay (getting you blacklisted)

How to Prevent It

Safe email handling
function sanitizeEmailInput(input) {
  // Remove all CR, LF, and null bytes
  return input.replace(/[\r\n\0]/g, '');
}

// Or validate and reject
function validateEmailInput(input) {
  if (/[\r\n]/.test(input)) {
    throw new Error('Invalid characters in input');
  }
  return input;
}

app.post('/contact', (req, res) => {
  const name = sanitizeEmailInput(req.body.name);
  const email = validateEmailInput(req.body.email);

  // Now safe to use in email
});

Does my email library prevent this?

Some modern libraries sanitize headers automatically, but many don't. Check your library's docs and test with newline payloads to be sure.

What about the message body?

The body comes after headers, so it's safe from this specific attack. That said, sanitize for XSS if the email is HTML.

Check Your Email Forms

Our scanner tests contact forms for header injection vulnerabilities.

Vulnerability Guides

Email Header Injection Explained