research/escaping-user-input-in-an-html-email

Escaping User Input in an HTML Email Template: What a Contact Form Message Can Inject, Tested in Node.js

Engineering Note · November 30, 2026 · 9 minute read · Email · Security · Node.js · Forms

If a contact form’s notification email is built by dropping the visitor’s text into an HTML template, the visitor can add HTML to your inbox. We built a typical template with a JavaScript template literal and fed it hostile input. Unescaped, a message turned into a real clickable link, a name loaded a remote image, a website field added an inline style, a javascript: URL became a link, and an HTML comment in the name hid everything after it. Escaping five characters fixed all of it, and 10,000 random strings came back as exactly the text that was typed. Three details still need care: links need a scheme check, line breaks must be added after escaping, and anything that goes into a header needs carriage returns and line feeds removed.

Everything below was run on Linux with Node.js 22.23.5. To see what an HTML parser makes of each email, we loaded it into Chromium 158.0.8127.36 through Playwright 1.63.0 and read back the elements, links and visible text. The outputs are real.

Why does a notification email need escaping at all?

Most small-business forms send the owner an email for each submission. The form handler usually builds an HTML body, because it looks better than plain text, and the quickest way to build one is a template string with the fields dropped in.

The person reading that email trusts it. It came from their own website, from their own sending address, often with their own logo at the top. Anything a visitor can make appear inside it borrows that trust: a link that says “Your invoice is overdue, pay here,” an image that tells a third party when the email was opened, or a block of text hidden from the reader.

Email clients differ a lot in what HTML they render and what they strip, so the honest test is what an HTML parser builds from the markup. If the parser sees an <a> element, a client that renders links will show a link.

What did the template look like?

This is the unescaped version, the quickest thing to write:

export function naive({ name, email, message, website }) {
  return `<p>New message from <strong>${name}</strong> (${email})</p>
<p>Website: <a href="${website}">${website}</a></p>
<p>${message.replace(/\n/g, '<br>')}</p>`;
}

We fed it eight inputs. One was an ordinary message. The others each tried one thing: plain tags in the name and message, a fake link in the message, a website value that closes the href quote and adds a style attribute, a javascript: URL, an <img> tag in the name, an HTML comment, and an ampersand case.

For each email we loaded the body into Chromium and listed the elements it built, the href of every link and the visible text.

What could the visitor add?

The ordinary message produced what you would expect: p, strong, p, a, p, br and one link to https://example.com. Then the hostile ones, from the real output:

tags      naive   elements=[p,strong,b,p,a,p,u] links=["https://example.com"]
fakeLink  naive   elements=[p,strong,p,a,p,a] links=["https://example.com","https://evil.example/login"]
breakAttr naive   elements=[p,strong,p,a,p] links=["https://example.com"] styled=1
jsUrl     naive   elements=[p,strong,p,a,p] links=["javascript:alert(1)"]
img       naive   elements=[p,strong,img,p,a,p] links=["https://example.com"]

Each line is a real change to the email:

  • tags: <b> and <u> became formatting. Harmless on its own, but it proves the door is open.
  • fakeLink: the message became a second, real link to https://evil.example/login, with link text the visitor chose.
  • breakAttr: a website value of https://example.com" style="font-size:40px" title="x closed the href quote early. The link points at a clean address, and the element now carries a style the visitor wrote.
  • jsUrl: javascript:alert(1) became a link. We did not test whether any email client would run it; it should never have been a link.
  • img: the name became an <img> pointing at a remote server. Any client that loads images would request it, telling that server the email was opened.

The comment case was the quietest and the most surprising. With Dana <!-- as the name, this is the whole visible text of the email:

naive "New message from Dana"

The email address, the website and the message, “Please call 502-555-0100 before noon.”, were all inside an unclosed comment, so the parser showed none of it. A visitor does not even need bad intent for this: a pasted snippet with a stray <!-- would do it.

The ampersand case showed a smaller bug. A visitor who typed Fish &amp; chips saw it displayed as Fish & chips. The text the visitor wrote was not the text the owner read.

What does escaping fix?

Escaping replaces the five characters that HTML treats as markup with their character references:

export function escapeHtml(s) {
  return String(s)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

The ampersand goes first. If it goes last, it re-escapes the references made a moment earlier. We checked: with & last, 5 < 6 became the source 5 &amp;lt; 6, which the reader sees as 5 &lt; 6.

With every field escaped, the hostile inputs produced the same structure as the ordinary message, and the visitor’s text appeared as text:

tags      escaped elements=[p,strong,p,a,p] links=["https://example.com/"]
                  text: New message from <b>Dana</b> (dana@example.com) | Website: https://example.com/ | Call me
fakeLink  escaped elements=[p,strong,p,a,p] links=["https://example.com/"]
img       escaped elements=[p,strong,p,a,p] links=["https://example.com/"]

The comment case now shows everything:

escaped "New message from Dana <!-- (dana@example.com)\n\nWebsite: https://example.com/\n\nPlease call 502-555-0100 before noon."

And Fish &amp; chips now reads Fish &amp; chips, as typed.

Does it hold for input we did not think of?

Eight hand-picked cases prove little. We generated 10,000 random strings from pieces chosen to cause trouble: <, >, &, both quotes, =, !, -, a backtick, a newline, é, and whole fragments such as <!--, <script>, &amp; and &lt;. Each string went into both a <strong> element and a quoted title attribute. The browser parsed each one, and we checked that exactly two elements came out and that both the text and the attribute equaled the original string.

Two runs, real output:

escaped: { cases: 10000, textMismatch: 0, attrMismatch: 0, extraElements: 0 }
naive:   { cases: 10000, textMismatch: 8612, extraElements: 3543 }
escaped: { cases: 10000, textMismatch: 0, attrMismatch: 0, extraElements: 0 }
naive:   { cases: 10000, textMismatch: 8616, extraElements: 3528 }

Unescaped, about 86% of the random strings were not shown as typed, and about 35% added elements. Escaped, none failed.

Escaping only < and > is a common shortcut. It is not enough inside an attribute. With &, < and > escaped but not quotes, the breakAttr value still produced <a href="https://example.com" style="font-size:40px">x</a>.

Escaping keeps a value inside its attribute. It does nothing about what the value means, and javascript:alert(1) has no characters to escape. The fix is to parse the URL and check its scheme:

export function safeUrl(s) {
  try {
    const u = new URL(String(s).trim());
    return (u.protocol === 'https:' || u.protocol === 'http:') ? u.href : null;
  } catch { return null; }
}

When safeUrl returns null, the template shows the value as escaped text instead of a link. In our run, the javascript: value and the breakAttr value (which new URL() rejected) both appeared as text with no link. One side effect: new URL() normalizes, so https://example.com became https://example.com/. A query string with & survived: the link’s href read back as https://example.com/?a=1&b=2.

Where do the line breaks go?

The naive template turns each newline into <br>. Done before escaping, the tags get escaped too. Real output for the message Line one\nLine two:

--- br then escape source: Line one&lt;br&gt;Line two
--- br then escape shown:  "Line one<br>Line two"
--- escape then br shown:  "Line one\nLine two"

Escape first, then add the line breaks. The only HTML in the body should be HTML your code wrote.

What about the subject line?

The subject is a header, not HTML, and the risk there is different. Headers are separated by a carriage return and line feed. If the form puts the visitor’s name in the subject and the name contains \r\n, the visitor can start a new header. We built a raw message by hand and listed its header names:

const name = 'Dana\r\nBcc: list@example.net';
const naive = `From: forms@example.com\r\nTo: owner@example.com\r\nSubject: New message from ${name}\r\n\r\nbody`;
naive  : [ 'From', 'To', 'Subject', 'Bcc' ]
cleaned: [ 'From', 'To', 'Subject' ]

The cleaned version replaced every run of CR and LF with a space, so the subject became New message from Dana Bcc: list@example.net: odd, but harmless. A mail library or sending API may clean headers for you. We did not test any library here, so check what yours does before relying on it.

A checklist for a form notification email

  • Escape every field that came from the visitor, in every place it appears, with & first.
  • Escape values inside attributes too, and always quote attributes.
  • Build a link only when new URL() parses the value and the protocol is http: or https:.
  • Escape first, then turn newlines into <br>.
  • Strip CR and LF from anything that goes into a header: subject, reply-to name, from name.
  • Send a plain-text part as well, so a client that ignores HTML still shows the message.
  • Test with the inputs above before you trust a template, including <!-- in a short field.

Our note on catching outgoing form email with a local SMTP sink shows how to run these tests against the real sending code without emailing anyone.

Limitations

  • We tested what Chromium’s HTML parser builds from each email. We did not send the emails to Gmail, Outlook, Apple Mail or other clients, which sanitize and render HTML in their own ways. A client that strips links or blocks images reduces the risk; it does not remove it.
  • The escaping function covers text between tags and values inside quoted attributes. It is not safe for unquoted attributes, inline <style> or <script>, or CSS values, and a form email should not put visitor text in those places.
  • The header test used a hand-built raw message and a simple header split. Real mail software parses headers with more rules, including folded lines, which we did not test.
  • The random test used 10,000 strings per run from a fixed set of pieces, in two runs. It shows the function held for those; it is not a proof.
  • We did not test templating engines that escape automatically. If you use one, check that the email template is not marked as raw or safe.

Sources

Frequently asked questions

Can someone inject HTML through my contact form email?

Yes, if the notification email puts the visitor's text into an HTML template without escaping it. In our test, a message containing an anchor tag became a real clickable link in the email, a name containing an img tag loaded a remote image, and an HTML comment in the name hid the rest of the message. The email arrives from your own form, so a fake link in it can look trustworthy.

Which characters do I need to escape in an HTML email?

Escape the ampersand first, then less-than, greater-than, the double quote and the single quote, turning them into &amp;, &lt;, &gt;, &quot; and &#39;. That covers text between tags and values inside quoted attributes. In our test it held for 10,000 random strings built from tricky characters, with no extra elements and the exact text shown.

Is escaping enough for a link the visitor typed?

No. Escaping stops the value from breaking out of the href attribute, but javascript:alert(1) contains no special characters and stays a link. Parse the value with new URL() and only build a link when the protocol is http: or https:. Otherwise show it as plain text.

Why does my email show &lt;br&gt; instead of line breaks?

The line breaks were turned into br tags before the text was escaped, so the escaping turned the tags into visible text. Escape the message first, then replace each newline with a br tag. The order matters, and our test showed both results.

Can a form field add headers to the email?

It can if the field goes into a header such as Subject or Reply-To without cleaning. In our test, a name containing a carriage return and line feed followed by Bcc: added a Bcc header to the raw message. Replace CR and LF with a space in anything that goes into a header, or let a mail library build the headers.

More from Research

← All research