How to Send Email from Node.js and TypeScript (Express and Next.js)

Send email from Node.js with one typed email API call and no SMTP server. Express and Next.js examples, HTML, attachments, replies and error codes.

By · · 17 min read

JSON code from this guide, in config.json, sending or reading email with Mailcycle

To send email from Node.js and TypeScript, most tutorials still reach for an SMTP library: find an SMTP server, copy a host, a port and a password into your config, pick the right TLS mode, and hope your host doesn’t block the port. That works, but it’s a lot of moving parts for “send this receipt”.

This tutorial does it with one typed HTTPS call instead. You’ll use mailcycle-sdk, Mailcycle’s TypeScript SDK, to send plain text and HTML email, attach files, send from an Express route and a Next.js route handler, handle errors by code, and then do the part a send-only API can’t: receive the reply in the same inbox and answer it in the thread.

Everything here runs on Node.js, and the same code runs on Deno, Bun and Cloudflare Workers. If your stack is in another language, the send email from any language guide covers all of them.

To read mail as well as send it, see How to receive email in Node.js: create an address, wait for a message, save attachments and handle a webhook.

Quick answer: how to send email in Node.js with TypeScript

Install mailcycle-sdk, create an API key on the Scale plan (or the free trial), and call mc.messages.send() with a from address on your account, a to address, a subject and a text body. It’s a single HTTPS request with typed options and a typed result, and there’s no SMTP server, port or TLS setting to configure.

npm install mailcycle-sdk
import { Mailcycle } from 'mailcycle-sdk';

const mc = await Mailcycle.withApiKey({ apiKey: process.env.MAILCYCLE_API_KEY! });

const { messageId } = await mc.messages.send({
  from: process.env.MAILCYCLE_FROM!, // an address on your Mailcycle account
  to: 'customer@example.com',
  subject: 'Your order has shipped',
  text: 'Order 1042 is on its way. Reply to this email if anything looks wrong.',
});

console.log('Sent', messageId);

The rest of this guide turns that into production code.

What you’ll build

By the end you’ll have:

  • a small lib/mailcycle.ts module that creates one client per process and never leaks the key,
  • an Express endpoint and a Next.js App Router route handler that email a sign-in code,
  • HTML email with a plain-text part, built from one template function,
  • email with a PDF attached and a logo shown inline,
  • a script that reads incoming mail and replies in the thread,
  • a send that waits for the customer’s reply, and a webhook that hears about new mail as it lands,
  • error handling that matches on stable error codes, with retries only where they’re safe,
  • a unit test that checks what you send without sending anything.
Flow: your TypeScript code calls the TypeScript SDK, Mailcycle sends the email from your address, and the recipient gets it
Your TypeScript code calls the TypeScript SDK, and Mailcycle sends the email from your address.

Prerequisites

  • Node.js 20 or later. We recommend Node.js 22 or later, kept on its latest patch: it has a built-in WebSocket, which the SDK uses to wait for mail. Check with node --version.
  • A TypeScript or JavaScript project using ES modules ("type": "module" in package.json, or a framework like Next.js that handles it).
  • A Mailcycle account on the Scale plan, or the free 7-day Scale trial. Sending with an API key starts at Scale. The trial needs no card.
  • An address on the account to send from. Step 3 shows how to find or create one.

Step 1: Install the TypeScript email SDK

npm install mailcycle-sdk
# or: pnpm add mailcycle-sdk / yarn add mailcycle-sdk / bun add mailcycle-sdk

The package has no dependencies and ships its own type declarations, so there’s no @types/ package to add. It’s ESM only. In an ES module, import { Mailcycle } from 'mailcycle-sdk' just works. From an older CommonJS file, load it with a dynamic import:

const { Mailcycle } = await import('mailcycle-sdk');

For a plain Node.js project, this tsconfig.json works well with the examples here. Next.js projects already have a suitable one.

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "strict": true,
    "skipLibCheck": true,
    "noEmit": true,
    "types": ["node"]
  }
}

To run a .ts file directly while you’re trying things out, use tsx: npx tsx --env-file=.env send.ts.

Step 2: Create an API key and keep it in an environment variable

  1. Open app.mailcycle.email/operator/signup and create an account. There’s no email or password: the account is a 12-word recovery phrase made on your device. Save it somewhere safe.
  2. In Plans & Billing, choose Start free trial if you’re not on Scale yet.
  3. Open API, then the Keys tab. Name the key (for example “Production web”) and choose Create key. Copy the token now: it starts with mak_ and is shown once.

Put it in a .env file that never gets committed:

# .env
MAILCYCLE_API_KEY=mak_...
MAILCYCLE_FROM=receipts-x7k2@example-pool.email
echo ".env" >> .gitignore

Node.js 20.6 and later read this file with node --env-file=.env, and Next.js loads .env.local for you.

Authentication and API keys in the docs cover what a key can and can’t do.

Step 3: Pick the address you send from

from must be an address on your account. Any other address is refused with 403 not_your_address. List what you have:

import { Mailcycle } from 'mailcycle-sdk';

const mc = await Mailcycle.withApiKey({ apiKey: process.env.MAILCYCLE_API_KEY! });

for (const address of await mc.addresses.list()) {
  console.log(address.id, address.emailAddress, address.receives ? 'receives' : 'send only');
}

To create one from code, give the client your recovery phrase as well. Mailcycle stores mail encrypted, sealed to keys derived from that phrase, and the SDK derives them on your machine. The phrase is never sent anywhere. That’s why creating an address that can receive mail needs it: the address’s public key comes from the phrase.

import { Mailcycle } from 'mailcycle-sdk';

const mc = await Mailcycle.withApiKey({
  apiKey: process.env.MAILCYCLE_API_KEY!,
  phrase: process.env.MAILCYCLE_PHRASE, // needed to create an address that receives mail
});

const address = await mc.addresses.create({ prefix: 'receipts', label: 'Order emails' });
console.log(address.emailAddress); // receipts-x7k2@…

New addresses are on Mailcycle’s shared domains. For mail your customers will see, you’ll usually want your own domain, like receipts@yourcompany.com: the Scale plan includes your own domains, and Your own domains walks through the DNS. Email addresses covers names, retention and labels.

Step 4: Send your first email from Node.js

Save the quick-answer snippet as send.ts, put a real recipient in to (your own inbox is best for a first test), and run it:

npx tsx --env-file=.env send.ts
Sent <…@…>

send resolves with a SendResult:

  • messageId is the Message-ID header the mail went out with. Store it if you want to match replies or support tickets to it later.
  • sentCopyId is the id of the copy in the address’s Sent folder, which mc.messages.get() takes. It’s null for an address that keeps no copy.

The Sent copy is sealed to the address’s key before it’s stored, like received mail. The message itself goes out in plain text, because the recipient’s mail server has to read it.

A few things the types will hold you to: subject and text are required, html is optional, and fromName sets the display name on the From line (Acme Support <receipts@…>). Each call sends to one recipient. To email several people, send one message each, which also keeps every reply in its own thread.

How to send email from an Express route

In a server you want one client for the whole process, created lazily, with the key read from the environment. Put this in lib/mailcycle.ts:

import { Mailcycle } from 'mailcycle-sdk';

function requireEnv(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`${name} is not set`);
  return value;
}

/** The address mail goes out from. It must belong to your Mailcycle account. */
export const fromAddress = () => requireEnv('MAILCYCLE_FROM');

let client: Promise<Mailcycle> | undefined;

/** One Mailcycle client per process, created on first use. */
export function mailcycle(): Promise<Mailcycle> {
  client ??= Mailcycle.withApiKey({
    apiKey: requireEnv('MAILCYCLE_API_KEY'),
    phrase: process.env.MAILCYCLE_PHRASE, // optional: only needed to read replies
  }).catch((error: unknown) => {
    client = undefined; // let the next request try again
    throw error;
  });
  return client;
}

Caching the promise rather than the client means concurrent first requests share one creation, and a failure isn’t cached forever. With an API key and no phrase, withApiKey makes no network call at all; with a phrase, it checks the phrase belongs to the key’s account once, up front.

Now the route. This one emails a six-digit sign-in code, a typical transactional email:

import express from 'express';
import { randomInt } from 'node:crypto';
import { MailcycleError } from 'mailcycle-sdk';
import { fromAddress, mailcycle } from './lib/mailcycle.js';

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

app.post('/api/sign-in-code', async (req, res) => {
  const email: unknown = req.body?.email;
  if (typeof email !== 'string' || !email.includes('@')) {
    res.status(400).json({ error: 'A valid email is required.' });
    return;
  }

  const code = randomInt(0, 1_000_000).toString().padStart(6, '0');
  // Store a hash of `code` against `email` with a short expiry here.

  try {
    const mc = await mailcycle();
    const { messageId } = await mc.messages.send({
      from: fromAddress(),
      fromName: 'Acme sign-in',
      to: email,
      subject: `Your Acme sign-in code: ${code}`,
      text: `Your sign-in code is ${code}. It expires in 10 minutes.\n\nIf you didn't ask for it, you can ignore this email.`,
    });
    res.status(202).json({ sent: true, messageId });
  } catch (error) {
    if (error instanceof MailcycleError && error.code === 'invalid_address') {
      res.status(400).json({ error: 'That email address looks wrong.' });
      return;
    }
    console.error('sign-in email failed', error);
    res.status(502).json({ error: 'Could not send the email. Try again shortly.' });
  }
});

app.listen(3000, () => console.log('Listening on http://localhost:3000'));

Try it:

curl -X POST http://localhost:3000/api/sign-in-code \
  -H "Content-Type: application/json" \
  -d '{"email":"you@example.com"}'

Two details worth copying. The handler awaits the send, so the client only hears “sent” once Mailcycle has accepted the message. And the error from the SDK is mapped to your own status codes and messages, so nothing about your email setup leaks to the caller.

How to send email from a Next.js route handler (App Router)

In Next.js, email is sent on the server: a route handler or a Server Action. Use the same lib/mailcycle.ts as above, saved at src/lib/mailcycle.ts, and add one line at the very top:

import 'server-only';

That’s the server-only package (npm install server-only). If a client component ever imports the module, the build fails instead of quietly shipping your key to the browser. Put the variables in .env.local with no NEXT_PUBLIC_ prefix, which keeps them server-side.

Then the route handler, src/app/api/sign-in-code/route.ts:

import { randomInt } from 'node:crypto';
import { MailcycleError } from 'mailcycle-sdk';
import { fromAddress, mailcycle } from '@/lib/mailcycle';

export const runtime = 'nodejs';

export async function POST(request: Request) {
  const body = (await request.json().catch(() => null)) as { email?: unknown } | null;
  const email = body?.email;
  if (typeof email !== 'string' || !email.includes('@')) {
    return Response.json({ error: 'A valid email is required.' }, { status: 400 });
  }

  const code = randomInt(0, 1_000_000).toString().padStart(6, '0');
  // Store a hash of `code` against `email` with a short expiry here.

  try {
    const mc = await mailcycle();
    const { messageId } = await mc.messages.send({
      from: fromAddress(),
      fromName: 'Acme sign-in',
      to: email,
      subject: `Your Acme sign-in code: ${code}`,
      text: `Your sign-in code is ${code}. It expires in 10 minutes.`,
    });
    return Response.json({ sent: true, messageId }, { status: 202 });
  } catch (error) {
    if (error instanceof MailcycleError && error.code === 'invalid_address') {
      return Response.json({ error: 'That email address looks wrong.' }, { status: 400 });
    }
    console.error('sign-in email failed', error);
    return Response.json({ error: 'Could not send the email. Try again shortly.' }, { status: 502 });
  }
}

runtime = 'nodejs' keeps the handler on the Node.js runtime, which is the default; we set it explicitly because the handler uses node:crypto. Reading MAILCYCLE_FROM inside the request, through fromAddress(), rather than at import time means next build doesn’t fail on a machine that doesn’t have the variable set.

A Server Action is often simpler for a form. The 'use server' directive keeps it on the server, and the form posts straight to it:

'use server';

import { fromAddress, mailcycle } from '@/lib/mailcycle';

export async function sendFeedbackReceipt(formData: FormData) {
  const email = String(formData.get('email') ?? '');
  const mc = await mailcycle();
  await mc.messages.send({
    from: fromAddress(),
    to: email,
    subject: 'We got your feedback',
    text: 'Thanks for writing in. We read every message, and you can reply to this one to add anything.',
  });
}

Validate email here as you would in the route handler, and the guards from the Express section apply here too.

How to send HTML email in TypeScript

Send html alongside text, always. The text part is what shows in previews and plain-text clients, and what screen readers and spam filters fall back on. Building both from one function keeps them in step, and a return type of Pick<SendOptions, ...> means TypeScript checks the shape against the SDK:

import type { SendOptions } from 'mailcycle-sdk';

const escapeHtml = (value: string) =>
  value.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!);

interface ShippedOrder {
  customerName: string;
  orderNumber: string;
  trackingUrl: string;
}

/** Subject, text and HTML for one email, built from the same data. */
export function orderShippedEmail(order: ShippedOrder): Pick<SendOptions, 'subject' | 'text' | 'html'> {
  const name = escapeHtml(order.customerName);
  const url = escapeHtml(order.trackingUrl);
  return {
    subject: `Order ${order.orderNumber} has shipped`,
    text: [
      `Hi ${order.customerName},`,
      '',
      `Order ${order.orderNumber} is on its way. Track it here: ${order.trackingUrl}`,
      '',
      'Reply to this email if anything looks wrong.',
    ].join('\n'),
    html: `<!doctype html>
<html>
  <body style="font-family: system-ui, sans-serif; line-height: 1.5; color: #111">
    <p>Hi ${name},</p>
    <p>Order <strong>${escapeHtml(order.orderNumber)}</strong> is on its way.</p>
    <p><a href="${url}" style="background:#111;color:#fff;padding:10px 16px;border-radius:6px;text-decoration:none">Track your parcel</a></p>
    <p>Reply to this email if anything looks wrong.</p>
  </body>
</html>`,
  };
}

Then spread it into the send:

import { fromAddress, mailcycle } from './lib/mailcycle.js';
import { orderShippedEmail } from './html-email.js';

const mc = await mailcycle();
await mc.messages.send({
  from: fromAddress(),
  to: 'customer@example.com',
  ...orderShippedEmail({ customerName: 'Sam', orderNumber: '1042', trackingUrl: 'https://example.com/track/1042' }),
});

Escape anything that came from a user before it goes into HTML: a customer named <script> shouldn’t become markup in someone’s inbox. Inline styles are still the safest choice for email clients. If you prefer components, any tool that renders React or MJML to an HTML string works: pass the string as html.

How to send email with attachments in Node.js

Files go in attachments as bytes. In Node.js, a Buffer is a Uint8Array, so whatever readFile returns can go straight in. Give an attachment a contentId and it becomes an inline image, shown where the HTML has <img src="cid:...">:

import { readFile } from 'node:fs/promises';
import { fromAddress, mailcycle } from './lib/mailcycle.js';

const mc = await mailcycle();

const [invoice, logo] = await Promise.all([readFile('./invoices/INV-1042.pdf'), readFile('./assets/logo.png')]);

await mc.messages.send({
  from: fromAddress(),
  to: 'customer@example.com',
  subject: 'Invoice INV-1042',
  text: 'Your invoice is attached. Thanks for your order.',
  html: '<p><img src="cid:logo" alt="Acme" width="120"></p><p>Your invoice is attached. Thanks for your order.</p>',
  attachments: [
    { filename: 'INV-1042.pdf', mimeType: 'application/pdf', content: invoice },
    { filename: 'logo.png', mimeType: 'image/png', content: logo, contentId: 'logo' },
  ],
});

A file you generate in memory works the same way. Encode a string to bytes with TextEncoder:

const csv = 'order,total\n1042,49.00\n';
const content = new TextEncoder().encode(csv); // a Uint8Array
export const attachment = { filename: 'orders.csv', mimeType: 'text/csv', content };

The SDK base64-encodes the bytes for you. A message takes up to 10 files and 3.5 MB of attachments between them, and program and script files such as .exe or .js are refused with attachment_blocked. mimeType defaults to application/octet-stream, so set it for anything you want the recipient’s mail client to preview.

How to reply to an email in Node.js and keep the thread

This is where an inbox you own pays off. Mail sent to your address lands in that address’s inbox, and the SDK can open it, because you gave it the phrase. To reply in the thread, pass the original message as replyTo:

import { Mailcycle } from 'mailcycle-sdk';

const mc = await Mailcycle.withApiKey({
  apiKey: process.env.MAILCYCLE_API_KEY!,
  phrase: process.env.MAILCYCLE_PHRASE, // opens the mail on this machine
});

const support = (await mc.addresses.list()).find((a) => a.emailAddress === process.env.MAILCYCLE_FROM);
if (!support) throw new Error('MAILCYCLE_FROM is not an address on this account');

const { messages } = await mc.messages.list(support.id, { folder: 'inbox', limit: 20 });

for (const message of messages.filter((m) => !m.read && m.opened)) {
  await mc.messages.send({
    from: support.emailAddress,
    to: message.replyTo, // Reply-To if the sender set one, otherwise From
    subject: message.subject.startsWith('Re:') ? message.subject : `Re: ${message.subject}`,
    text: `Thanks, we've got your message and will get back to you today.\n\n> ${message.text.split('\n').join('\n> ')}`,
    replyTo: message, // threads the reply under the original
  });
  await mc.messages.markRead(message.id);
}

Every Message comes back already decrypted, with from, fromName, subject, text, html, safeHtml, messageId, attachments and more, all typed. If you ever render a received message in a web page, use safeHtml, which has remote images, stylesheets and embeds removed. A message that can’t be opened, because the client has no phrase or the wrong one, comes back with opened: false and empty content rather than throwing, which is why the loop checks m.opened. Pages come newest first; pass nextCursor back as cursor for the next page. Reading mail has the folders, stars and moves.

How to receive email in Node.js: wait for a reply

Sometimes the code that sent a message wants the answer: a confirmation, a document, a “yes”. waitFor resolves with the next matching message, already opened. Take the time before sending and pass it as since, so a fast reply isn’t missed:

import { Mailcycle, MailcycleError } from 'mailcycle-sdk';

const mc = await Mailcycle.withApiKey({
  apiKey: process.env.MAILCYCLE_API_KEY!,
  phrase: process.env.MAILCYCLE_PHRASE,
});

const addresses = await mc.addresses.list();
const support = addresses.find((a) => a.emailAddress === process.env.MAILCYCLE_FROM)!;

const since = new Date(); // take the time before sending
await mc.messages.send({
  from: support.emailAddress,
  to: 'customer@example.com',
  subject: 'Can you confirm your delivery address?',
  text: 'Reply with the address you would like order 1042 sent to.',
});

try {
  const reply = await mc.messages.waitFor({
    inboxId: support.id,
    from: 'customer@example.com',
    since,
    timeoutMs: 10 * 60_000,
  });
  console.log(reply.subject);
  console.log(reply.text);
  for (const file of reply.attachments) console.log('attachment', file.index, file.filename, file.size);
} catch (error) {
  if (error instanceof MailcycleError && error.code === 'timeout') {
    console.log('No reply in 10 minutes. Check again later, or use a webhook.');
  } else {
    throw error;
  }
}

waitFor listens on Mailcycle’s event stream, a WebSocket, so it hears about new mail the moment it lands. Where no WebSocket is available, it checks the address every five seconds instead, which is why passing inboxId is a good habit. It filters on from and subject (case-insensitive “contains”), and rejects with code timeout if nothing matches in time. The same pattern is handy in end-to-end tests: send a sign-up from your app, then waitFor the verification email and pull the link out of message.text.

To save the files from a message, fetch each attachment’s bytes. They’re decrypted on your machine:

import { writeFile } from 'node:fs/promises';
import type { Mailcycle, Message } from 'mailcycle-sdk';

export async function saveAttachments(mc: Mailcycle, message: Message) {
  for (const file of message.attachments) {
    if (!file.stored) continue; // the part had no body
    const bytes = await mc.messages.attachment(message, file.index); // opened on this machine
    await writeFile(`./downloads/${message.id}-${file.index}-${file.filename.replace(/[\\/]/g, '_')}`, bytes);
  }
}

Receive email with a webhook in production

A long-running wait suits scripts and tests. A web app should be told when mail arrives instead. Add a webhook in the app under API > Webhooks for message.received, store its whsec_ secret as MAILCYCLE_WEBHOOK_SECRET, and verify every delivery against the raw body before you trust it:

import { after } from 'next/server';
import { verifyWebhookSignature } from 'mailcycle-sdk';
import { mailcycle } from '@/lib/mailcycle';

export const runtime = 'nodejs';

export async function POST(request: Request) {
  const rawBody = await request.text(); // the raw body, before any parsing
  const valid = await verifyWebhookSignature(
    process.env.MAILCYCLE_WEBHOOK_SECRET!,
    rawBody,
    request.headers.get('Mailcycle-Signature'),
  );
  if (!valid) return new Response('Bad signature', { status: 401 });

  const event = JSON.parse(rawBody) as { id: string; type: string; payload: { messageId?: string } };
  if (event.type === 'message.received' && event.payload.messageId) {
    const messageId = event.payload.messageId;
    // Answer within 10 seconds; do the slow work after. Deduplicate on event.id.
    after(async () => {
      const mc = await mailcycle();
      const message = await mc.messages.get(messageId);
      console.log('New mail from', message.from, '-', message.subject);
    });
  }
  return new Response(null, { status: 204 });
}

Events carry ids, never content, so the handler fetches the message by id and the SDK opens it locally. That needs MAILCYCLE_PHRASE set on the server, so treat that variable with the same care as the key. verifyWebhookSignature also refuses a timestamp more than five minutes old. Mailcycle retries failed deliveries, and an event can arrive more than once, so deduplicate on event.id. In Express, read the body with express.text({ type: 'application/json' }) on that route so you have the raw string to verify.

How to handle errors when sending email in TypeScript

Every API failure throws a MailcycleError with the HTTP status and a stable code. Match on code, never on the message text. The SDK adds a few codes of its own with status 0, such as network_error (no answer came back), phrase_required (the client needs the phrase for that call) and timeout (from waitFor).

The codes you’ll meet when sending:

Code Status What it means What to do
not_your_address 403 from isn’t an address on this account Fix the config
invalid_address 400 to is malformed Tell the user
plan_required 403 API key sending needs Scale or above Upgrade, or start the trial
domain_not_sending 409 Your own domain isn’t sending yet Check the domain under Domains
attachments_too_large, message_too_large 413 Files or message too big Send a link instead
attachment_blocked, too_many_attachments 400 A blocked file type, or more than 10 files Fix the request
rate_limited 429 Too many requests in a short time Back off and retry
daily_send_limit 429 Today’s sending allowance is used Queue it; resumes 00:00 UTC
sending_paused 503 Sending is paused for the day Queue it; resumes 00:00 UTC
network_error 0 No response reached you The send may or may not have happened

Here’s a wrapper that retries only where retrying is safe. A 429 or a 5xx means the API refused or failed the request, so trying again can’t send the message twice. A network_error is different: the request may have gone through before the connection dropped, so it isn’t retried blindly.

import { MailcycleError, type Mailcycle, type SendOptions, type SendResult } from 'mailcycle-sdk';

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

/** Codes where the API refused the send, so trying again cannot send twice. */
const RETRY_LATER = new Set(['rate_limited', 'maintenance', 'read_only']);

export async function sendWithRetry(mc: Mailcycle, options: SendOptions, attempts = 4): Promise<SendResult> {
  for (let attempt = 1; ; attempt++) {
    try {
      return await mc.messages.send(options);
    } catch (error) {
      if (!(error instanceof MailcycleError)) throw error;

      switch (error.code) {
        case 'not_your_address': // `from` is not on this account
        case 'invalid_address': // `to` is malformed
        case 'attachment_blocked': // .exe, .js, .ps1 and similar
        case 'attachments_too_large':
        case 'message_too_large':
        case 'too_many_attachments':
          throw error; // a bug in the request: fix it, do not retry

        case 'plan_required': // API key sending needs Scale or above
        case 'payment_required':
        case 'address_paused':
        case 'domain_not_sending': // your own domain, sending not switched on yet
          throw error; // an account problem: alert a person

        case 'daily_send_limit': // resumes at 00:00 UTC
        case 'sending_paused':
          throw error; // queue it for tomorrow instead
      }

      const retryable = RETRY_LATER.has(error.code) || error.status >= 500;
      if (!retryable || attempt >= attempts) throw error;
      await sleep(2 ** attempt * 1_000 + Math.random() * 500); // 2s, 4s, 8s, plus jitter
    }
  }
}

The API also sends a Retry-After header with a 429. The SDK’s error doesn’t carry headers, so the wrapper backs off on a schedule instead. For the numbers behind 429, see Rate limits, and Errors lists every code.

In a busy app, don’t send inside the request at all: put the email on a job queue and let a worker call sendWithRetry. The request stays fast, and a daily_send_limit becomes a delayed job rather than a failed sign-up.

How to test email sending without sending real email

Every client takes a fetch option, so a unit test can hand it a fake and check exactly what would have gone out, with no network and no real key. Here it is with Node’s built-in test runner:

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { Mailcycle } from 'mailcycle-sdk';

test('sends the order email from the receipts address', async () => {
  const calls: { url: string; body: any }[] = [];
  const fakeFetch: typeof fetch = async (input, init) => {
    calls.push({ url: String(input), body: JSON.parse(String(init?.body)) });
    return Response.json({ sent: true, messageId: '<test@mailcycle>', sentCopyId: 'msg_test' });
  };

  const mc = await Mailcycle.withApiKey({ apiKey: 'mak_test', fetch: fakeFetch });
  const result = await mc.messages.send({
    from: 'receipts@yourcompany.com',
    to: 'customer@example.com',
    subject: 'Order 1042 has shipped',
    text: 'On its way.',
  });

  assert.equal(result.sentCopyId, 'msg_test');
  assert.equal(calls[0]!.url, 'https://api.mailcycle.email/messages/send');
  assert.equal(calls[0]!.body.to, 'customer@example.com');
});
npx tsx --test send.test.ts

The fake can also return an error body, like Response.json({ code: 'rate_limited', message: 'Slow down' }, { status: 429 }), to test your retry path. For full end-to-end tests, use a real test address and waitFor, as in the section above.

The same send with cURL

Under the hood, send is one POST /messages/send with a bearer token. Here’s the raw HTTP call, which is handy for checking a key or debugging from a shell:

curl https://api.mailcycle.email/messages/send \
  -H "Authorization: Bearer $MAILCYCLE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "from": "receipts-x7k2@example-pool.email",
    "to": "customer@example.com",
    "subject": "Your order has shipped",
    "text": "Order 1042 is on its way."
  }'
{ "sent": true, "messageId": "<…>", "sentCopyId": "msg_…" }

A threaded reply adds inReplyTo (the Mailcycle message id) and inReplyToHeader (its Message-ID), and attachments go in as base64 content. Sending mail documents every field. What cURL can’t easily do is the other half: received mail is stored sealed, so reading it means deriving keys from your phrase, which the SDK does for you.

Nodemailer and SMTP vs the Mailcycle SDK

Nodemailer is the long-standing way to send email from Node.js, and it’s a good library: if you already have SMTP credentials from a provider you’re happy with, it does the job. Here’s what it looks like with an SMTP server:

import nodemailer from 'nodemailer';

const transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST,
  port: 587,
  secure: false, // STARTTLS on 587; use 465 with secure: true for implicit TLS
  auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
});

await transporter.sendMail({
  from: '"Acme" <receipts@yourcompany.com>',
  to: 'customer@example.com',
  subject: 'Your order has shipped',
  text: 'Order 1042 is on its way.',
});

The difference is less about the send call and more about everything around it:

Nodemailer + SMTP Mailcycle SDK
What you need first An SMTP server or provider, its host, port and credentials An API key and an address on your account
Transport SMTP over TCP; ports 587, 465 or 25, and a TLS mode to match HTTPS to one API
Network Some hosts restrict outbound SMTP ports Ordinary outbound HTTPS
Runtimes Node.js Node.js 20+, Deno, Bun, Cloudflare Workers
Types Community types in @types/nodemailer Bundled; options, results and errors are typed
Errors SMTP response codes and transport errors A MailcycleError with a stable code
Receiving replies Not included; add an IMAP client and a mailbox Same SDK: list, waitFor, webhooks
Threading a reply Set inReplyTo and references headers yourself Pass the message as replyTo
Copy of what you sent Depends on the server Kept in Sent, encrypted at rest
Testing A test SMTP server or a stub transport A fake fetch

Choose an API like Mailcycle’s when you’d rather not run SMTP at all, when your code runs somewhere SMTP is awkward, or when you need the replies as well as the sends. It’s built for mail from addresses you own: transactional and notification email, sign-in and verification flows, and app and agent replies.

Sending email from an AI agent in TypeScript

If you’re building an agent in TypeScript, the SDK gives it the same powers as your app: its own address, waitFor the reply, answer in the thread. If the agent runs in an MCP client like Claude Code, you don’t need to write any of that yourself: Mailcycle’s MCP server gives it an inbox with reply-only defaults. See give Claude Code its own email address, the AI agents guide, or Mailcycle for agents.

Troubleshooting

plan_required on every send. API key sending needs Scale or above. Start the trial under Plans & Billing, or upgrade. The key keeps working once the plan includes it.

not_your_address. from must match an address on the account exactly. Print mc.addresses.list() and copy it from there.

phrase_required. You called something that needs keys, such as creating an address that receives mail or opening an attachment, on a client made without phrase.

Messages come back with opened: false. The client has no phrase, or a phrase from a different account. With an API key, a phrase from another account fails up front with phrase_mismatch.

waitFor never resolves. Check since was taken before the send, that from and subject really match, and that timeoutMs is long enough. Without a WebSocket it polls every five seconds, which needs inboxId.

ERR_REQUIRE_ESM or “cannot use import statement”. The package is ESM only. Use "type": "module", or await import('mailcycle-sdk') from CommonJS.

Next steps

You can now send email from Node.js and TypeScript, from Express and Next.js, with HTML, attachments and threaded replies, and receive the answers in the same inbox. From here:

FAQ

How do I send an email from Node.js without an SMTP server?

Use an email API over HTTPS instead of SMTP. With Mailcycle, npm install mailcycle-sdk, create an API key on the Scale plan, and call mc.messages.send({ from, to, subject, text }). There's no SMTP host, port or TLS mode to configure.

What is a good Nodemailer alternative for TypeScript?

If you don't want to run or rent an SMTP server, an HTTP email API with a typed SDK is the usual alternative. mailcycle-sdk is written in TypeScript, has no dependencies, and also receives the replies to what you send, in the same inbox. If you already have SMTP credentials you're happy with, an HTTP API is the other route.

Can I send email from a Next.js client component?

No, and you shouldn't try. Sending needs your API key, and anything in a client component ships to the browser. Send from a route handler (app/api/.../route.ts) or a Server Action, keep the key in an environment variable without the NEXT_PUBLIC_ prefix, and add import 'server-only' to the module that creates the client.

Does mailcycle-sdk work with plain JavaScript?

Yes. The package is an ES module with TypeScript types bundled, so plain JavaScript works the same way; you just don't get type checking. Use import { Mailcycle } from 'mailcycle-sdk' in an ES module, or await import('mailcycle-sdk') from CommonJS.

How do I send the same email to several people in Node.js?

Each send call goes to one recipient, so loop over your recipients and send one message each. That also gives every person their own thread for replies. Each send counts towards the plan's daily sending allowance.

Can I send email from my own domain?

Yes. The Scale plan includes your own domains, so you can send from an address like receipts@yourcompany.com. Follow Your own domains to verify the domain, then create addresses on it.

Does it run on Deno, Bun or Cloudflare Workers?

Yes. mailcycle-sdk uses only fetch and WebCrypto, so it runs on Node.js 20 or later, Deno, Bun and Cloudflare Workers. Keep it server-side wherever you run it, because the API key must stay secret.

How do I receive email in Node.js?

Create an address with the SDK (pass your recovery phrase so it can receive), then call mc.messages.waitFor() to wait for the next matching message, or mc.messages.list() to read the inbox. For production, a webhook tells your server the moment mail arrives.

Do I need a paid plan to send email with an API key?

Sending with an API key needs the Scale plan or above. You can try it with the free 7-day Scale trial, which needs no card. See pricing for the plans.

Send email from any language