To send email from Express, add a route that validates the request and then hands the message to an email API or an SMTP server. Node 18 and later include fetch, so the API route needs no extra package. For SMTP, Nodemailer is the standard library. The examples below use Express 5 and ES modules.
Set up the app and the key
npm install express
Store the key in an environment variable, not in code:
MAILCANDOR_KEY=mc_live_xxxxxxxxxxxxxxxx
Node 20.6 and later can load a .env file with node --env-file=.env server.js, so you do not need the dotenv package for this.
Option 1: fetch and an email API
Put the send in one small function so every route uses the same code and error handling:
// email.js
export async function sendEmail(message, idempotencyKey) {
const headers = {
Authorization: `Bearer ${process.env.MAILCANDOR_KEY}`,
'Content-Type': 'application/json',
};
if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey;
const res = await fetch('https://api.mailcandor.com/v1/emails', {
method: 'POST',
headers,
body: JSON.stringify(message),
});
const body = await res.json();
if (!res.ok) {
throw new Error(`${body.error.type}: ${body.error.message}`);
}
return body.id;
}
Then call it from a route. This contact form endpoint sends the message to your team with the visitor’s address in reply_to:
// server.js
import express from 'express';
import { sendEmail } from './email.js';
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.post('/contact', async (req, res) => {
const { email, message } = req.body ?? {};
if (typeof email !== 'string' || !email.includes('@') || !message) {
return res.status(400).json({ error: 'Email and message are required' });
}
const id = await sendEmail({
from: 'Contact form <forms@acme.com>',
to: 'team@acme.com',
reply_to: email,
subject: `New message from ${email}`,
text: String(message),
});
res.status(202).json({ id });
});
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: 'Something went wrong' });
});
app.listen(3000);
In Express 5, an async handler that throws passes the error to the error middleware at the bottom, so you do not need try/catch in every route. On Express 4, wrap the body in try/catch and call next(err).
The API answers with 202 and an id as soon as the email is queued. Delivery, bounces and spam complaints arrive later as webhooks, which you can receive on another Express route.
Retries without duplicates
If a request times out, you cannot tell whether the email was accepted. Pass an idempotency key that is unique to the email, such as order-1042-receipt:
await sendEmail(receipt, `order-${order.id}-receipt`);
A retry with the same key returns the first response instead of sending again.
Option 2: Nodemailer over SMTP
npm install nodemailer
Create the transport once at startup and reuse it in every route:
// mailer.js
import nodemailer from 'nodemailer';
export const mailer = nodemailer.createTransport({
host: 'smtp.mailcandor.com',
port: 465,
secure: true,
auth: { user: 'mailcandor', pass: process.env.MAILCANDOR_KEY },
});
// server.js
import express from 'express';
import { mailer } from './mailer.js';
const app = express();
app.use(express.json());
app.post('/welcome', async (req, res) => {
const { email } = req.body ?? {};
if (typeof email !== 'string' || !email.includes('@')) {
return res.status(400).json({ error: 'A valid email is required' });
}
const info = await mailer.sendMail({
from: 'Acme <hello@acme.com>',
to: email,
subject: 'Welcome to Acme',
html: '<p>Thanks for signing up.</p>',
text: 'Thanks for signing up.',
});
res.json({ messageId: info.messageId });
});
app.listen(3000);
Use port 465 with secure: true, or port 587 with secure: false so Nodemailer upgrades the connection with STARTTLS. To catch bad credentials at boot instead of on the first email, call await mailer.verify() before app.listen. See the Nodemailer SMTP guide for pooling and attachments.
Keep the request fast
Sending inside the request is fine for a contact form. For anything that runs in bulk, such as a digest to every user, put the work on a queue (BullMQ, a cron job or your platform’s background jobs) and let the route return straight away. The API option is already fast because it only queues the email; SMTP waits for the server to accept the whole message.
Protect public endpoints
Any route that sends email on request will be found by bots. At minimum:
- Validate and length-limit every field.
- Add rate limiting, for example with the
express-rate-limitpackage. - Add a hidden honeypot field and reject requests that fill it in.
- Send to your own inbox. Never let the request choose the
toaddress on a public form. - Escape user input before putting it in
html, or send it astext.
Common errors
A 400 from your own route usually means express.json() is missing, so req.body is undefined. An EAUTH error from Nodemailer means wrong SMTP credentials, and a timeout usually means your host blocks the SMTP port; the API over port 443 avoids that.
Which should you choose?
| Email API (fetch) | Nodemailer (SMTP) | |
|---|---|---|
| Extra packages | None | nodemailer |
| Time per request | One HTTPS call | SMTP conversation per email, unless pooled |
| Delivery events | Webhooks with an email id | Usually none |
| Idempotent retries | Idempotency-Key header |
Not built in |
| Best for | New Express apps | Existing Nodemailer code |
Both are reasonable in Express. The general SMTP vs API comparison goes into the trade-offs.
Before you send: verify your domain
Email from a domain without SPF, DKIM and DMARC is likely to land in spam, whichever option you use. Add your domain in your provider’s dashboard and publish the DNS records it gives you. The SPF, DKIM and DMARC guide explains each one.