Skip to content
Tellwing

Send email from Node.js with an API

Node.js 18 or later ships fetch, so sending an email is one HTTP request: no SMTP setup, no packages to install and retries that never duplicate. Everything in this guide is tested with a key that sends nothing.

Updated November 24, 20264 min read

Why an API and not SMTP

With SMTP your process opens a connection, negotiates TLS and waits for the server on every email; if something fails halfway, you don’t know whether it went out. With an API you make a request, get an ID back and hear about the delivery or the bounce by webhook.

The full differences are in SMTP or API. Here is the code.

What you need

  • Node.js 18 or later, which ships fetch. Nothing to install.
  • A test key (tw_test_…) from Organization → API, in the TELLWING_API_KEY environment variable. Never in your code or in the browser.
  • To send for real, your verified domain and a tw_live_ key. API Free includes 3,000 emails a month for nothing.

The request, with fetch

http
// send-email.mjs: Node.js 18 or later ships fetch, so there is nothing to install.
const res = await fetch("https://api.tellwing.com/v1/messages", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.TELLWING_API_KEY}`,
"Content-Type": "application/json",
// The same key on a retry returns the stored response: the email never goes out twice.
"Idempotency-Key": "order-A-1042-confirmation",
},
body: JSON.stringify({
to: "ana@example.com",
subject: "Your order A-1042 is confirmed",
html: "<p>Thanks for your purchase, Ana.</p>",
}),
});
const data = await res.json();
if (!res.ok) throw new Error(`${data.error.code}: ${data.error.message}`);
console.log(data.id, data.delivery_id);

The API answers 202 with id, status, recipients (the ones counted against the quota), suppressed (addresses skipped because they bounced before) and delivery_id, the same one your webhooks carry.

One function for your whole app

In production you want a single function that retries what can be retried. Since the Idempotency-Key is stored for 24 hours, retrying with the same key never sends twice:

http
// email.mjs: one function for your whole app, with safe retries.
const API = "https://api.tellwing.com/v1/messages";
export async function sendEmail(message, idempotencyKey) {
for (let attempt = 1; attempt <= 3; attempt++) {
const res = await fetch(API, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.TELLWING_API_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey,
},
body: JSON.stringify(message),
});
if (res.ok) return res.json();
// 429: wait for Retry-After. 5xx: wait a little. With the same Idempotency-Key it never duplicates.
if (res.status === 429 || res.status >= 500) {
const wait = Number(res.headers.get("Retry-After") ?? attempt * 2);
await new Promise((r) => setTimeout(r, wait * 1000));
continue;
}
// 402 quota_exceeded, 403 domain_not_verified, 422 recipient_suppressed…: retrying won't fix them.
const { error } = await res.json();
throw Object.assign(new Error(error.message), { code: error.code, status: res.status });
}
throw new Error("Tellwing did not answer after 3 attempts");
}

With a template your team built in the builder, you send its ID and its variables instead of the HTML:

http
await sendEmail(
{
to: user.email,
template_id: "YOUR_TEMPLATE_ID",
variables: { name: user.firstName, code: "482913" },
},
`login-code-${user.id}-${Date.now()}`
);

Express, Next.js or NestJS

The function works the same in any framework, always on the server: in Next.js, from a route handler or a server action; never from a client component, because it would expose your key. If you send when a purchase completes, use the order ID in the Idempotency-Key: a double click or a retry from your payment processor won’t send two receipts.

Webhooks: verify the signature

Every event (email.delivered, email.bounced, email.complained) arrives signed in the Tellwing-Signature header. Verify it with the raw request body and your secret:

http
import crypto from "node:crypto";
// Use the RAW body (Buffer/string), never the parsed JSON.
export function verifyTellwingSignature(rawBody, signatureHeader, secret) {
const parts = Object.fromEntries(signatureHeader.split(",").map((kv) => kv.split("=")));
const t = Number(parts.t);
if (!t || Math.abs(Date.now() / 1000 - t) > 300) return false; // 5 minutes
const expected = crypto.createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex");
const received = Buffer.from(parts.v1 ?? "", "hex");
const wanted = Buffer.from(expected, "hex");
return received.length === wanted.length && crypto.timingSafeEqual(received, wanted);
}

In Express, receive the webhook with express.raw(), which keeps the raw body, and deduplicate by the event’s id: a retry carries the same one.

Test it without sending anything

With the test key, each sandbox address gives the result its name says: delivered@sandbox.tellwing.com is delivered, bounced@ bounces, complained@ complains and suppressed@ is treated as an address that already bounced. Add +anything before the at sign for unique addresses in your tests.

Read what it costs and how to go live in Email API for developers, see every endpoint in the documentation or create your free account.

Frequently asked questions

Do I need to install a package to send email from Node.js?

No. Since Node.js 18, fetch is built in, and Tellwing’s API is REST with JSON: one request, one email.

Where do I keep the API key?

In a server environment variable, like TELLWING_API_KEY. Never in the repository or in the browser: whoever has it can send in your name.

How do I avoid sending the same email twice?

With the Idempotency-Key header: if you repeat the request with the same key within 24 hours, the API returns the stored response and doesn’t send again.

How much does sending email from Node.js with Tellwing cost?

API Free comes with every account: 3,000 transactional emails a month, up to 100 a day. API Pro costs $20 for 50,000 or $35 for 100,000, and the yearly plan bills 11 months for 12.