# Send Email with Node.js: A Complete API Tutorial

> Send email with Node.js using fetch and an email API: HTML, templates, attachments, batches of 100 and safe retries, with copy-paste code. No SMTP needed.

Canonical: https://www.cresca.xyz/blog/send-email-nodejs
Author: Lalit Kumar Jangid
Published: 2026-10-27
Last updated: 2026-10-30

You can **send email with Node.js** using nothing but the `fetch` that ships with the runtime. There is no SMTP server to run and no mail library to configure: your code makes one HTTPS request to Cresca, gets an email id back, and Cresca delivers the message from your own domain within seconds. Below, a ten-line script grows into a small module you can drop into an Express app or a worker, with HTML and plain text, templates with variables, attachments, batches of 100, retries that cannot double-send, and an Express route.

**TL;DR**

- Node.js 18 and later have a global `fetch`, so the email code needs no npm packages.
- Send `POST https://api.cresca.xyz/api/v1/emails` with `Authorization: Bearer <key>` and a JSON body with `from`, `to`, `subject` and `html`.
- `fetch` only rejects when the network fails, so check `res.ok` yourself.
- Pass an `Idempotency-Key`, retry only 429s, 5xx and network errors, and batch up to 100 emails per call.

## Before you start

- **Node.js 18 or later.** Both `fetch` and `AbortSignal.timeout()` are globals there. The examples are ES modules with top-level `await`, so use `.mjs` files or set `"type": "module"` in package.json.
- **A domain, a sender and a key in Cresca.** Verify the domain on the [Sending Domains](https://app.cresca.xyz/sending-domains) page, add an active sender on it (say `hello@acme.com`), and create a key with *Sending access* on [API keys](https://app.cresca.xyz/api-keys). The [email API quickstart](https://www.cresca.xyz/docs/quickstart) walks through all three, DNS records included.
- **The key in `process.env.CRESCA_API_KEY`.** Keys start with `cr_live_` and are shown once. Locally, put it in a `.env` file and start Node with `node --env-file=.env` (Node 20.6 and later), or load it with the `dotenv` package on older versions. Keep `.env` out of git.

## Send email with Node.js: the basic request

Save this as `send.mjs` and run `node send.mjs` with the key in your environment:

```js
const res = await fetch('https://api.cresca.xyz/api/v1/emails', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.CRESCA_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    from: 'Acme <hello@acme.com>',
    to: 'ana@example.com',
    subject: 'Welcome to Acme',
    html: '<p>Hi Ana, your account is ready.</p>',
  }),
});

const body = await res.json();
if (!res.ok) throw new Error(`${body.name}: ${body.message}`);
console.log(body.id);
```

Note that with `fetch`, a 403 or a 422 does not throw. The promise resolves with a response whose `ok` is `false`, which is why the script checks `res.ok` and throws with the API's `name` and `message`. On success you get `200 OK` and the email's id. Store it with the record that triggered the email.

```json
{ "id": "4ef9a417-02e9-4d39-ad75-9611e0fcc33c" }
```

A few payload rules. `to` accepts a string or an array. `from` is a bare address or `Name <address>`. Send `html` alone and Cresca builds the plain-text part; add `text` to write that part yourself, or send only `text` for a plain email. Optional fields are `cc`, `bcc`, `reply_to`, `tags` and `scheduled_at`, which can be up to 30 days ahead.

## A reusable cresca() module with timeouts and retries

For a server, `cresca.mjs` wraps the request with three additions.

- **A timeout.** `fetch` has no per-request timeout option, so a stalled connection could hold your handler for minutes. `AbortSignal.timeout(10_000)` aborts after 10 seconds. The abort and any network failure both land in the `catch` block, and both are retried.
- **An `Idempotency-Key`.** If the response is lost after Cresca has accepted the email, retrying with the same key returns the original result and no second email goes out. Keys are kept for 24 hours. Derive them from the event, for example `welcome/user-123` or `invoice/inv-2026-0042`. A timestamp or `crypto.randomUUID()` defeats the purpose, because every retry would carry a new key. Details in [idempotency](https://www.cresca.xyz/docs/idempotency).
- **Retry rules based on the error `name`.** Error bodies look like `{"statusCode": 422, "name": "validation_error", "message": "..."}`. The `name` is stable and the message wording may change, so never match on the message. The loop retries 5xx responses, `429 rate_limit_exceeded` and `409 concurrent_idempotent_requests`. It waits for `retry-after` when Cresca sends it and otherwise backs off 1, 2 and 4 seconds with a little jitter. Any other 4xx is thrown at once, since the same request would get the same answer.

```js
// cresca.mjs: a small client for the Cresca email API (Node.js 18+).
const API_URL = 'https://api.cresca.xyz/api/v1';
const ATTEMPTS = 4;

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// 1s, 2s, 4s... plus up to 250 ms of jitter.
const backoff = (attempt) => 2 ** (attempt - 1) * 1000 + Math.random() * 250;

export class CrescaError extends Error {
  constructor(status, name, message) {
    super(`${status} ${name}: ${message}`);
    this.status = status;
    this.code = name;
  }
}

export async function cresca(path, payload, { idempotencyKey } = {}) {
  for (let attempt = 1; ; attempt++) {
    let res;
    try {
      res = await fetch(API_URL + path, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${process.env.CRESCA_API_KEY}`,
          'Content-Type': 'application/json',
          ...(idempotencyKey && { 'Idempotency-Key': idempotencyKey }),
        },
        body: JSON.stringify(payload),
        signal: AbortSignal.timeout(10_000),
      });
    } catch (err) {
      // Network error or timeout: the idempotency key makes a retry safe.
      if (attempt === ATTEMPTS) throw err;
      await sleep(backoff(attempt));
      continue;
    }

    const body = await res.json().catch(() => ({}));
    if (res.ok) return body;

    const name = body.name ?? 'unknown_error';
    const retryable =
      res.status >= 500 ||
      (res.status === 429 && name !== 'monthly_quota_exceeded') ||
      name === 'concurrent_idempotent_requests';
    if (!retryable || attempt === ATTEMPTS) {
      throw new CrescaError(res.status, name, body.message ?? res.statusText);
    }
    const retryAfter = Number(res.headers.get('retry-after'));
    await sleep(retryAfter > 0 ? retryAfter * 1000 : backoff(attempt));
  }
}
```

The error class keeps the API's error name in `err.code`, not `err.name`, because `err.name` is what Node prints at the start of every stack trace. Calling the module looks like this, and a timeout or a 429 halfway through can no longer cause a duplicate:

```js
import { cresca } from './cresca.mjs';

const { id } = await cresca(
  '/emails',
  {
    from: 'Acme <hello@acme.com>',
    to: user.email,
    subject: 'Welcome to Acme',
    html: `<p>Hi ${escapeHtml(user.firstName)}, your account is ready.</p>`,
  },
  { idempotencyKey: `welcome/${user.id}` },
);
```

Anything a user typed has to be escaped before it goes into an HTML string. `escapeHtml` stands for your own function or a package such as `escape-html`. The template approach in the next section removes the problem.

## Move the HTML out of template literals

Template literals full of markup get hard to maintain. In Cresca's template editor you build the email once and mark the dynamic parts with triple braces, such as `{{{RESET_LINK}}}`. After you publish it, your Node code passes the template's alias and a `variables` object and nothing else. The rules, from [templates and variables](https://www.cresca.xyz/docs/templates):

- Sends use the *published* version, so editing a draft never changes live email.
- Variable values are HTML-escaped for you.
- A missing variable with no fallback makes the API return `422 validation_error` with the variable's name.
- `from` and `subject` come from the template unless your payload sets them.

```js
await cresca(
  '/emails',
  {
    to: user.email,
    template: {
      id: 'password-reset', // the template's alias or id
      variables: { NAME: user.firstName, RESET_LINK: resetUrl },
    },
  },
  { idempotencyKey: `password-reset/${resetRequest.id}` },
);
```

Every reset request is its own event with its own id, so a user who clicks "forgot password" twice gets two emails, which is what they expect.

## Attach a file from disk or a Buffer

`readFile` from `node:fs/promises` returns a `Buffer`, and `buffer.toString('base64')` is all the encoding the API needs. If you generate the PDF in memory, skip the read and encode that buffer directly.

```js
import { readFile } from 'node:fs/promises';

const pdf = await readFile('invoices/inv-2026-0042.pdf');

await cresca(
  '/emails',
  {
    from: 'Acme Billing <billing@acme.com>',
    to: customer.email,
    subject: 'Your invoice INV-2026-0042',
    html: '<p>Thanks for your payment. Your invoice is attached.</p>',
    attachments: [
      { filename: 'inv-2026-0042.pdf', content: pdf.toString('base64'), content_type: 'application/pdf' },
    ],
  },
  { idempotencyKey: 'invoice/inv-2026-0042' },
);
```

The limits are 20 attachments and 7 MB in total per email. Each item takes `filename`, `content` and an optional `content_type`. To show an image inside the HTML, give it a `content_id` and reference it as `<img src="cid:logo">`. Executable types such as .exe and .js are rejected, and you cannot attach by URL yet, so download remote files yourself and send the bytes.

## Send a batch of up to 100 emails

For a digest or a notice to many users, map the users to payloads and send them to `POST /emails/batch` in slices of 100:

```js
const emails = users.map((user) => ({
  from: 'Acme <hello@acme.com>',
  to: user.email,
  subject: 'Your weekly summary',
  html: renderSummary(user),
}));

for (let i = 0; i < emails.length; i += 100) {
  const { data } = await cresca('/emails/batch', emails.slice(i, i + 100), {
    idempotencyKey: `weekly-summary/2026-10-27/${i / 100}`,
  });
  console.log(`Batch ${i / 100}: ${data.length} emails accepted`);
}
```

- Each item takes the same fields as a single send, except `attachments` and `scheduled_at`.
- A batch is all or nothing. One invalid email means none are sent, and the error message gives the bad item's zero-based index. In this loop, `i` plus that index points at the user.
- The response is `{"data": [{"id": "..."}, ...]}`, in the same order as your array.
- A batch counts as one request against your rate limit, which is how you get to thousands of emails a minute. The per-second limit is 2 on Free, 10 on Professional, 20 on Premium, 50 on Ultra and 100 on Enterprise.

The loop awaits each chunk before starting the next. Firing every chunk at once with `Promise.all` is the quickest way to hit `rate_limit_exceeded`. Each chunk also has its own key, so if the job crashes you can rerun it from the top within 24 hours and chunks that already went out are not sent again.

## Send email from an Express route

Send from the server, after the work that triggers the email has succeeded. Browser code must never call the API, because the key would ship to every visitor.

```js
import express from 'express';
import { cresca, CrescaError } from './cresca.mjs';

const app = express();
app.use(express.json());

app.post('/signup', async (req, res) => {
  const user = await createUser(req.body); // your own code

  try {
    await cresca(
      '/emails',
      { to: user.email, template: { id: 'welcome', variables: { NAME: user.firstName } } },
      { idempotencyKey: `welcome/${user.id}` },
    );
  } catch (err) {
    // The account exists either way; log and let a job retry the email later.
    console.error('Welcome email failed', err instanceof CrescaError ? err.code : err);
  }

  res.status(201).json({ id: user.id });
});

app.listen(3000);
```

The `try`/`catch` does two jobs. The account already exists, so a failed email should not turn the signup into an error. And in Express 4 a rejected promise inside an async handler never reaches your error middleware; it becomes an unhandled rejection, which stops the process by default in current Node versions. Log `err.code` and retry from a job. For slower work, a queue such as BullMQ is the better home for the send; the unchanged idempotency key keeps its retries safe.

## Nodemailer or an email API?

Nodemailer is the standard SMTP client for Node.js and a good fit when you already run a mail server. An HTTP API leaves less to operate: no SMTP transport or connection pool, no blocked SMTP ports on your host, JSON errors with a stable `name`, and idempotency keys so a retry cannot send twice. Cresca has no SMTP relay yet, so with Cresca you use the API as shown here.

## Errors your Node.js code should expect

When the module gives up, it throws a `CrescaError` carrying `err.status` and `err.code`. The common codes are below; the [errors page](https://www.cresca.xyz/docs/errors) lists the rest.

| err.status | err.code | Cause | What cresca() does |
| --- | --- | --- | --- |
| 403 | `invalid_from_address` | `from` is not an active sender on a verified domain. | Throws at once. Fix the sender. |
| 422 | `validation_error` | A field is invalid, or a template variable is missing. | Throws at once. Fix the payload. |
| 422 | `missing_required_field` | No `to`, `from` or `subject`, and no template that supplies them. | Throws at once. |
| 429 | `rate_limit_exceeded` | More requests per second than your plan allows. | Waits for `retry-after` (or backs off), then retries. |
| 429 | `monthly_quota_exceeded` | The plan's monthly email allowance is used up. | Throws at once. |
| 409 | `concurrent_idempotent_requests` | A request with the same key is still being processed. | Retries after a short wait. |
| 5xx | `application_error` | Something failed on Cresca's side. | Retries with backoff. |

Network errors and timeouts are rethrown as the original error after the fourth attempt, so check `err instanceof CrescaError` before you read `err.code`. A recipient on your suppression list (an earlier hard bounce, complaint or unsubscribe) is skipped without an error and the request still succeeds. See [suppression](https://www.cresca.xyz/docs/suppression).

## Check that the email was delivered

A `200` only tells you Cresca accepted the email. To see what happened next, open [Transactional](https://app.cresca.xyz/transactional) in the app for each email's timeline, or fetch the email by the id you stored. That lookup needs a full-access key, because a sending-access key cannot read logs:

```bash
curl https://api.cresca.xyz/api/v1/emails/4ef9a417-02e9-4d39-ad75-9611e0fcc33c \
  -H "Authorization: Bearer $CRESCA_API_KEY"
```

Watch `last_event`: it goes from `queued` to `sent`, then to `delivered` or `bounced`. Every status is listed under [email lifecycle](https://www.cresca.xyz/docs/email-lifecycle).

## Frequently asked questions

### Can I send email straight from React or other browser code?

No. Anyone can read a key in browser code with the developer tools and send email as you. Have the frontend call your own Express route or serverless function, and send from there with a sending-access key kept in an environment variable.

### Does the module work with TypeScript, Bun and Deno?

Yes. It only uses `fetch`, `AbortSignal.timeout` and JSON, which Node.js 18 and later, Bun and Deno all provide. For TypeScript, rename the file to `.ts` and add a type for the payload.

### Is there an official Cresca SDK for Node.js?

No, and you do not need one. The API is plain HTTPS and JSON, so `fetch` or the HTTP client your project already uses is enough. `cresca.mjs` is short; copy it into your codebase and change it as you like.

## The same tutorial in other languages

[Python](https://www.cresca.xyz/blog/send-email-python) · [PHP](https://www.cresca.xyz/blog/send-email-php) · [Go](https://www.cresca.xyz/blog/send-email-golang) · [Ruby](https://www.cresca.xyz/blog/send-email-ruby) · [Java](https://www.cresca.xyz/blog/send-email-java) · [C# and .NET](https://www.cresca.xyz/blog/send-email-csharp) · [Next.js](https://www.cresca.xyz/blog/send-email-nextjs) · [Laravel](https://www.cresca.xyz/blog/send-email-laravel) · [Django](https://www.cresca.xyz/blog/send-email-django) · [Ruby on Rails](https://www.cresca.xyz/blog/send-email-rails)

The [send email API guide](https://www.cresca.xyz/blog/send-email-api) documents every field of the Emails API with cURL examples. The [transactional email API overview](https://www.cresca.xyz/blog/transactional-email-api) gives the bigger picture, and [SMTP vs API](https://www.cresca.xyz/blog/smtp-vs-api-sending) helps if you are still choosing.

## Start sending

Cresca is free for 30 days: 250 contacts, 1,000 emails and 20 AI emails, no credit card. API email shares the plan's allowance with campaigns. **[Create your account](https://app.cresca.xyz/signup)**, verify a domain, and paste `cresca.mjs` into your project. The [quickstart](https://www.cresca.xyz/docs/quickstart) and the [API docs](https://www.cresca.xyz/docs) cover the rest.
