For the complete site index, see llms.txt. Docs index: llms-docs.txt. Marketing corpus: llms-full.txt. Docs corpus: llms-full-docs.txt. Prefer markdown URLs where available (append .md).. Product skill: skill.md. Pricing: pricing.md. Docs MCP: /docs/mcp.

Tutorials/

How to Send Email in Node.js: Nodemailer vs API (2026)

Pranav Patel

Pranav Patel

Co-founderยท12 min read

How to Send Email in Node.js: Nodemailer vs API (2026)
Summary

Send email from Node.js with Nodemailer over SMTP or with an email API. Complete TypeScript examples for HTML email, attachments, React Email templates, retries with idempotency keys and error handling.

There are two ways to send email from Node.js: over SMTP with Nodemailer, or over HTTPS with an email API SDK. Use Nodemailer when you need to stay provider-neutral or the target only speaks SMTP. Use an API when you control the code and want structured errors, safe retries and no MIME handling.

This guide covers both with TypeScript examples you can copy, then goes through the parts that break in production: errors, retries, attachments and templates.

Using a framework? See the guides for Next.js, SvelteKit, Remix and Cloudflare Workers. Writing Python instead? Read how to send email in Python.


Which approach should you use?

Nodemailer (SMTP)
Email API (HTTPS)
Transport
SMTP on port 587 (STARTTLS)
HTTPS on port 443
Blocked by firewalls or serverless?
Sometimes
Almost never
Errors
SMTP reply codes as strings
JSON with status, message and fix
Safe retries
No, a retry can send twice
Yes, with an idempotency key
Edge runtimes and Workers
No raw TCP sockets
Works anywhere fetch works
Switch providers
Change host and password
Change the SDK
Templates, scheduling, tags
Build them yourself
Built in

Short version: if you write the code, use the API. If you are configuring software that only accepts SMTP credentials, use Nodemailer or the software's SMTP settings.


Prerequisites

  1. Node.js 18 or later (for native fetch)
  2. A verified sending domain with SPF, DKIM and DMARC. Sending from an unverified domain is the most common reason mail lands in spam.
  3. An API key from the Reloop dashboard. Keys start with rl_.
env
RELOOP_API_KEY=rl_your_api_key

Never commit this file. Load it with node --env-file=.env (Node 20.6+) or your framework's env loader.


Install

bash
npm install reloop-email

Create one shared client

lib/reloop.ts
1import { Reloop } from "reloop-email";
2
3if (!process.env.RELOOP_API_KEY) {
4 throw new Error("Missing RELOOP_API_KEY");
5}
6
7export const reloop = new Reloop({ apiKey: process.env.RELOOP_API_KEY });

Send your first email

send.ts
1import { reloop } from "./lib/reloop";
2
3const { response, emailError } = await reloop.mail.send({
4 from: "Acme <hello@mail.acme.com>",
5 to: "user@example.com",
6 subject: "Welcome to Acme",
7 html: "<h1>Welcome!</h1><p>Thanks for signing up.</p>",
8 text: "Welcome! Thanks for signing up.",
9});
10
11if (emailError) {
12 console.error(emailError.status, emailError.body.message, emailError.body.fix);
13 process.exit(1);
14}
15
16console.log("Sent", response.id);

Run it:

bash
npx tsx --env-file=.env send.ts

The SDK does not throw on API or network errors. It returns either response or emailError, so you cannot forget a try/catch. Network failures come back with status: 0.

Send from an Express route

typescript
1import express from "express";
2import { reloop } from "./lib/reloop";
3
4const app = express();
5app.use(express.json());
6
7app.post("/api/contact", async (req, res) => {
8 const { email, message } = req.body as { email?: string; message?: string };
9
10 if (!email?.includes("@") || !message) {
11 return res.status(400).json({ error: "Email and message are required" });
12 }
13
14 const { response, emailError } = await reloop.mail.send({
15 from: "Acme Website <contact@mail.acme.com>",
16 to: "support@acme.com",
17 reply_to: email,
18 subject: `New message from ${email}`,
19 text: message,
20 });
21
22 if (emailError) {
23 return res.status(502).json({ error: "Could not send message" });
24 }
25
26 res.json({ id: response.id });
27});
28
29app.listen(3000);

Note the reply_to. Put the visitor's address there, not in from. You can only send from domains you have verified, and spoofing a visitor's domain fails DMARC.


Method 2: Send email with Nodemailer (SMTP)

Install

bash
npm install nodemailer
npm install -D @types/nodemailer

Create a transporter and send

typescript
1import nodemailer from "nodemailer";
2
3const transporter = nodemailer.createTransport({
4 host: "smtp.reloop.sh",
5 port: 587,
6 secure: false, // STARTTLS; use port 2587 if 587 is blocked
7 auth: {
8 user: "reloop",
9 pass: process.env.RELOOP_API_KEY,
10 },
11});
12
13const info = await transporter.sendMail({
14 from: '"Acme" <hello@mail.acme.com>',
15 to: "user@example.com",
16 subject: "Welcome to Acme",
17 html: "<h1>Welcome!</h1><p>Thanks for signing up.</p>",
18 text: "Welcome! Thanks for signing up.",
19});
20
21console.log("Sent", info.messageId);

Create the transporter once and reuse it. Creating one per request opens a new TCP and TLS connection every time.

Verify the connection at startup

typescript
await transporter.verify(); // throws if host, port or credentials are wrong

If verify() hangs or times out, the port is blocked or secure does not match the port. The SMTP ports guide covers every error.

Can I use Gmail with Nodemailer?

You can, with an App Password, but not for a product. Personal Gmail accounts are limited to about 500 recipients a day, every message comes from @gmail.com, and bulk sending from a personal account gets it suspended. Use a provider with your own domain.


Send HTML email with React Email

Writing email HTML by hand means nested tables and inline styles. React Email lets you write components instead.

bash
npm install @react-email/components @react-email/render react react-dom
emails/welcome.tsx
1import { Body, Button, Container, Html, Text } from "@react-email/components";
2
3export function WelcomeEmail({ name }: { name: string }) {
4 return (
5 <Html>
6 <Body style={{ fontFamily: "sans-serif" }}>
7 <Container>
8 <Text>Hi {name}, welcome to Acme.</Text>
9 <Button href="https://acme.com/start">Get started</Button>
10 </Container>
11 </Body>
12 </Html>
13 );
14}

Pass the component as react. The Reloop SDK renders it to HTML for you:

tsx
1import { WelcomeEmail } from "./emails/welcome";
2
3await reloop.mail.send({
4 from: "Acme <hello@mail.acme.com>",
5 to: "user@example.com",
6 subject: "Welcome to Acme",
7 react: <WelcomeEmail name="Ada" />,
8});

With Nodemailer, render it yourself: html: await render(<WelcomeEmail name="Ada" />) from @react-email/render.

If your team edits copy without deploying code, store templates in Reloop instead and send them by ID with template: { id, variables }. See templates.


Attachments

Both methods accept base64 content.

typescript
1import { readFile } from "node:fs/promises";
2
3const pdf = await readFile("./invoice-1042.pdf");
4
5await reloop.mail.send({
6 from: "Acme Billing <billing@mail.acme.com>",
7 to: "user@example.com",
8 subject: "Your invoice #1042",
9 text: "Your invoice is attached.",
10 attachments: [
11 {
12 filename: "invoice-1042.pdf",
13 content: pdf.toString("base64"),
14 content_type: "application/pdf",
15 },
16 ],
17});

Keep attachments small. Large files hurt deliverability and many inboxes reject messages over 25 MB. For anything big, send a signed download link instead.


Retries without duplicate emails

A request times out. Did the email go out? With SMTP you cannot know, and retrying might send it twice. The API solves this with an Idempotency-Key header: retry with the same key and Reloop returns the original result instead of sending again.

typescript
1async function sendReceipt(orderId: string, to: string): Promise<void> {
2 for (let attempt = 1; attempt <= 3; attempt++) {
3 const res = await fetch("https://reloop.sh/api/mail/v1/send", {
4 method: "POST",
5 headers: {
6 "Content-Type": "application/json",
7 "x-api-key": process.env.RELOOP_API_KEY ?? "",
8 "Idempotency-Key": `receipt-${orderId}`,
9 },
10 body: JSON.stringify({
11 from: "Acme <orders@mail.acme.com>",
12 to,
13 subject: `Receipt for order ${orderId}`,
14 text: "Thanks for your order.",
15 }),
16 }).catch(() => null);
17
18 if (res?.ok) return;
19 if (res && res.status < 500 && res.status !== 409 && res.status !== 429) {
20 throw new Error(`Send failed: ${res.status} ${await res.text()}`);
21 }
22 await new Promise((r) => setTimeout(r, 2 ** attempt * 250));
23 }
24 throw new Error(`Send failed after retries for order ${orderId}`);
25}

Base the key on the business event (receipt-${orderId}), not a random UUID per attempt. That way, even a retry from a different worker cannot double-send.

Retry on network errors, 409 (same key still in flight), 429 (rate limited) and 5xx. Do not retry other 4xx errors. An invalid address or unverified domain will fail the same way every time.


Do not send email inside the request

Sending inline adds 100 to 500 ms to every signup and fails the request if the provider is slow. For anything beyond a contact form:

  1. Write the job to a queue (BullMQ, pg-boss, SQS) in the same transaction as the business change.
  2. Return the HTTP response.
  3. Send from a worker with the retry logic above.

This is the same pattern Reloop uses internally. See how we built our delivery queue with BullMQ.


Production checklist

  • API key in an environment variable, never in client bundles or git
  • Sending domain verified with SPF, DKIM and DMARC
  • from on your verified domain; user addresses go in reply_to
  • Both html and text bodies
  • One shared client or transporter, not one per request
  • Idempotency keys on anything retried
  • Sends happen in a background job, not the request path
  • Webhooks for bounces and complaints so you stop mailing bad addresses
  • Disposable addresses blocked at signup (how)

FAQ

Yes. Node has no built-in SMTP client, but you can call any email API with the native fetch available since Node 18. Writing your own SMTP client on top of net and tls is possible but not worth it.

Nodemailer is free and open source. It is only a client: you still need an SMTP server to send through, such as an email provider, your own Postfix or a Gmail account for personal use.

Usually because the sending domain is not authenticated, or the From domain does not match the domain that signed the message. Set up SPF, DKIM and DMARC, send from your own domain, and include a plain-text body.

Use the HTTP API. Edge runtimes and Cloudflare Workers do not allow raw SMTP sockets, and some serverless platforms block outbound SMTP ports. See the Cloudflare Workers guide for a fetch-only example.

Pass up to 50 addresses in to, cc or bcc for a single message. For personalised bulk mail, send one message per recipient from a queue, or use campaigns, which handle unsubscribe headers and throttling for you.


W: 320.0px180R20โˆ 45.0ยฐ

Ship your first email with Reloop
in minutes.

Open-source, deliverability-focused, and yours to self-host or run on Reloop Cloud. No lock-in, no rewrite later.

Reloop