Email Header Injection Explained

Share

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). If attackers can inject newlines into any header field, they can add arbitrary headers.

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 do not. Check your library's documentation and test with payloads containing newlines to be sure.

What about the message body?

The body is generally safe from header injection (since it comes after headers), but you should still sanitize for XSS if the email is HTML.

Check Your Email Forms

Our scanner tests contact forms for header injection vulnerabilities.

Start Free Scan
Vulnerability Guides

Email Header Injection Explained