Guide · JavaScript & TypeScript
How to send email with Express
Send transactional email from an Express route: a contact form or sign-up handler that calls the Stack Emails API and returns errors cleanly.
Last reviewed November 2026
1. Set up
You need a Stack Emails API key (create one free) and a verified sending domain.
npm install express
export STACKEMAILS_API_KEY=se_live_xxxxxxxxxxxx
2. Send your first email
import express from "express";
const app = express();
app.use(express.json());
async function sendEmail(payload) {
const res = await fetch("https://stackemails.com/v1/emails", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.STACKEMAILS_API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error?.message ?? "Send failed");
return data;
}
app.post("/contact", async (req, res) => {
const { name, email, message } = req.body ?? {};
if (!email || !message) return res.status(422).json({ error: "Email and message are required." });
try {
await sendEmail({
from: "Acme Website <forms@mail.acme.com>",
to: "support@acme.com",
reply_to: email,
subject: `New message from ${name || email}`,
text: message,
});
res.json({ ok: true });
} catch (err) {
res.status(502).json({ error: err.message });
}
});
app.listen(3000);
A successful request returns 202 with the message id, for example { "id": "msg_5b1f0c6c2a8e4e0f", "status": "queued" }. Errors return a JSON body with error.code and error.message (see errors).
Notes
- Use
reply_toso replying in your inbox goes to the visitor, while the From address stays on your verified domain. - Rate-limit public form routes (for example with
express-rate-limit) so bots can't use your quota.
Production checklist
- Keep the API key in an environment variable or secret manager, never in client-side code.
- Add an
Idempotency-Keyheader to retries so a timeout never sends twice (idempotency). - Subscribe to webhooks for bounces and complaints.
- Check your domain's SPF, DKIM and DMARC records.
- Start from a tested email template for password resets, receipts and invites.