research/catching-form-email-with-a-local-smtp-sink
Testing That a Form's Email Is Actually Sent: Catching Outgoing SMTP With a Local Sink
Engineering Note · November 20, 2026 · 8 minute read · Email · Testing · Node.js · Forms
To test that a contact form really sends its email, point the form’s outgoing mail settings at a local SMTP sink, a small mail server that accepts every message and keeps it instead of delivering it, then assert on what arrived. SMTP (Simple Mail Transfer Protocol) is the protocol servers use to hand mail to each other, so the code under test runs exactly as it would in production, up to the moment the message leaves. Our sink caught two real bugs in a stand-in form handler: replying “thanks” before the send had finished, so a refused recipient or a dead server still showed the visitor a success message, and a Reply-To header that accepted a line break typed into the email field. It also showed that a mail server which never answers held the request for 30 seconds by default.
Everything below was run with Node.js 22.23.5 on Linux, using Nodemailer 10.6.0 to send, smtp-server 3.21.6 as the sink and mailparser 3.14.5 to read what arrived. All addresses are on example.test, and nothing left the machine. The outputs are the real ones from these runs. This note goes with today’s article, When a Spreadsheet Has Become Software, and with our earlier monitoring article, which recommends a monthly hand test of the contact form.
What does the sink look like?
The sink is about 30 lines. It accepts mail without a password, refuses any recipient on a list we pass in (so we can test refusals), and parses each message into an object a test can inspect.
// sink.mjs: a local SMTP server that keeps every message instead of delivering it.
import { SMTPServer } from 'smtp-server';
import { simpleParser } from 'mailparser';
export async function startSink({ port = 2525, reject = [] } = {}) {
const messages = [];
const server = new SMTPServer({
authOptional: true,
disabledCommands: ['STARTTLS'],
logger: false,
onRcptTo(address, session, cb) {
if (reject.includes(address.address)) {
const err = new Error('Mailbox unavailable');
err.responseCode = 550;
return cb(err);
}
cb();
},
onData(stream, session, cb) {
simpleParser(stream).then((mail) => {
messages.push({
envelopeFrom: session.envelope.mailFrom.address,
envelopeTo: session.envelope.rcptTo.map((r) => r.address),
mail,
});
cb();
}, cb);
},
});
await new Promise((resolve) => server.listen(port, '127.0.0.1', resolve));
return { messages, close: () => new Promise((r) => server.close(r)) };
}
We keep the envelope recipients separately from the headers. The envelope is the list of addresses the sending server actually delivers to; the To, Cc and Bcc headers are only text inside the message. A header injection that adds a Bcc line matters only if it changes the envelope or the headers a person acts on, so a test should check both.
What does the form handler send?
The handler is the part of a contact form that turns the submitted fields into an email. We wrote two versions of it, because the difference between them is the most common way this goes wrong:
// form.mjs
import nodemailer from 'nodemailer';
export function makeTransport(port, extra = {}) {
return nodemailer.createTransport({
host: '127.0.0.1', port, secure: false, ignoreTLS: true, ...extra,
});
}
function buildMessage(f) {
return {
from: 'Website form <forms@example.test>',
to: 'leads@example.test',
replyTo: f.email,
subject: `New enquiry from ${f.name}`,
text: `Name: ${f.name}\nEmail: ${f.email}\nPhone: ${f.phone}\n\n${f.message}`,
};
}
// Version A: send and reply straight away (the common shape).
export function handleFormFireAndForget(fields, transport, log = console.error) {
transport.sendMail(buildMessage(fields), (err) => {
if (err) log(`send failed: ${err.code ?? ''} ${err.message}`);
});
return { status: 200, body: 'Thanks, we will be in touch.' };
}
// Version B: wait for the server to accept the message before answering.
export async function handleForm(fields, transport) {
try {
const info = await transport.sendMail(buildMessage(fields));
return { status: 200, body: 'Thanks, we will be in touch.', accepted: info.accepted, rejected: info.rejected };
} catch (err) {
return { status: 502, body: 'Sorry, that did not go through. Please call us.', error: `${err.code ?? ''} ${err.responseCode ?? ''} ${err.message}`.trim() };
}
}
In production the only change is the transport settings: the real host, port, TLS and credentials. The test swaps them for 127.0.0.1:2525.
What did the tests show?
One script ran six cases against the sink. The happy path first, with ordinary form values:
1 happy path: 200 | envelope to: leads@example.test | reply-to: ann@example.test | subject: New enquiry from Ann Lee
The message arrived, addressed to the leads inbox, with the visitor’s address as Reply-To so that pressing Reply answers the customer. A test asserts each of these, plus that the body contains the message text.
Does a line break in the name add a Bcc?
We submitted the name Ann\r\nBcc: someone@example.test. \r\n is the line break that separates email headers, so if it reached the header block unchanged it would start a new Bcc: line.
2 header injection: 200 | envelope to: leads@example.test | bcc header: (none) | subject: "New enquiry from Ann Bcc: someone@example.test"
Nodemailer replaced the line break with a space. The subject looks odd, but no header was added and the envelope still had one recipient.
The email field was a different story. It goes into replyTo, which Nodemailer parses as an address list rather than plain text. We ran two values through it:
"ann@example.test\r\nBcc: someone@example.test" -> 200 | envelope to: leads@example.test | reply-to: | bcc header: (none)
"ann@example.test, someone@example.test" -> 200 | envelope to: leads@example.test | reply-to: ann@example.test + someone@example.test | bcc header: (none)
Neither added a recipient at send time. But the Reply-To header changed. Reading it back with mailparser showed what the first value had become:
"ann@example.test Bcc": someone@example.test;
That is an address group, a rarely used email syntax: a display name followed by a list of addresses. The parsed address list for that header was empty (hence the blank reply-to: above), but the address inside the group is someone@example.test, and a mail program honoring the group could send the reply there. The second value, with a comma, gave a Reply-To with two addresses. In both cases whoever answers the lead could end up writing to an address the visitor chose. The fix is to validate the email field as exactly one address, with no line breaks or commas, before it goes anywhere near a header.
Non-ASCII text came through intact:
3 non-ascii subject: "New enquiry from José Peña 🌮"
What happens when the server refuses the recipient?
The sink was told to refuse leads@example.test with SMTP reply code 550 and the text “Mailbox unavailable”. Both handler versions ran against it:
4 recipient refused: fire-and-forget -> 200 | log: send failed: EENVELOPE Can't send mail - all recipients were rejected: 550 Mailbox unavailable
awaited -> 502 | EENVELOPE 550 Can't send mail - all recipients were rejected: 550 Mailbox unavailable
messages caught: 0
The fire-and-forget version told the visitor “Thanks, we will be in touch” and wrote the failure to a log nobody was reading. The awaited version returned an error page that asks them to call. No message was stored either way.
What happens when no mail server is running?
5 server down: fire-and-forget -> 200 | log: send failed: ESOCKET connect ECONNREFUSED 127.0.0.1:2599
awaited -> 502 | ESOCKET connect ECONNREFUSED 127.0.0.1:2599
Same pattern. A changed SMTP password, an expired account or a firewall rule would look like this in production: the visitor sees success and the lead is lost.
What happens when the server never answers?
The last case used a plain TCP server that accepts the connection and then says nothing. The client waits for a greeting from the server that never comes.
6 silent server, greetingTimeout=default: 502 ETIMEDOUT Greeting never received | 30.0 s
6 silent server, greetingTimeout=3000: 502 ETIMEDOUT Greeting never received | 3.0 s
With default settings the awaited handler held the visitor’s request for 30 seconds before failing. Setting greetingTimeout: 3000 in the transport options made it fail in 3. If the form waits for the send, which it should, set timeouts short enough that a visitor is still on the page when the error appears. Nodemailer also has connectionTimeout and socketTimeout options for the other stages of the conversation; we only measured the greeting.
How do you run this in a test suite?
Start the sink before the tests and stop it after, give the application the sink’s host and port through its normal configuration (an environment variable is usual), and assert on sink.messages. Clear the array between tests. Use a port above 1024 so no special permissions are needed. For the failure cases, start the sink with a reject list, or point the application at a port where nothing is listening.
We would assert at least these for every form that sends email:
- Exactly one message arrived, with the expected envelope recipients.
- Reply-To is the visitor’s address and nothing else.
- The subject and body contain the submitted fields.
- When the send fails, the visitor sees a failure message with another way to reach you.
- A line break or comma in the email field is rejected before sending.
Limitations
- The sink tests the handoff to a mail server, not delivery. Whether a real provider puts the message in an inbox depends on SPF, DKIM and DMARC (see Email That Arrives) and the provider’s filters. Send a real test message by hand each month as well.
- We tested Nodemailer 10.6.0 only. Other mail libraries, and other versions of Nodemailer, may handle line breaks in headers, address groups and timeouts differently. Run the same cases against whatever your form uses.
- Many forms now send through a provider’s HTTPS API instead of SMTP. The same idea applies (point the code at a local fake and check what it received), but the failure messages and timeouts differ and were not tested here.
- The sink disabled STARTTLS and authentication to stay simple. A production server that requires both can fail in ways this setup does not exercise, such as a certificate error or a rejected password.
- Timings are single runs on one machine. The 30-second default and the 3-second setting matched to a tenth of a second, but we did not measure variation.
Related reading
- Knowing Your Website Is Broken Before a Customer Tells You
- Testing a form flow that depends on bot checks and AI
- Email That Arrives: SPF, DKIM and DMARC for a Small Business Domain
Frequently asked questions
What is an SMTP sink?
An SMTP sink is a mail server that accepts messages and stores them instead of delivering them. Point your application's outgoing mail settings at it during tests, and every email the code sends lands where a test can read it. Nothing reaches a real inbox, so tests can run as often as you like.
Why does my contact form say thanks when the email never arrives?
A common cause is a handler that starts sending the email and replies to the visitor without waiting for the result. In our test that version returned 200 when the mail server refused the recipient and when no server was running at all; the error only reached a log. Waiting for the send and showing a fallback message on failure makes the visitor's screen match what happened.
How long does Nodemailer wait for an SMTP server that does not respond?
With Nodemailer 10.6.0 and no timeout settings, our handler waited 30.0 seconds for the greeting from a server that accepted the connection and never spoke, then failed with ETIMEDOUT. Setting greetingTimeout to 3000 milliseconds made it fail after 3.0 seconds. A visitor is unlikely to wait half a minute for a form.
Can a contact form be used to inject email headers?
In our test Nodemailer turned a line break in the name field into a space in the subject, and no Bcc header appeared. A line break in the email field, used as Reply-To, did change that header: the reply address became the injected one. Validate the email field as a single address before using it in any header.
Does a local SMTP sink prove the email will reach the inbox?
No. It proves your code built the right message and handed it to a mail server correctly. Whether a real provider delivers it to the inbox depends on SPF, DKIM and DMARC, the provider's reputation checks and the recipient's filters. Test those separately, with a real message to a real inbox once a month.