Lettermint Node.js SDK

The official JavaScript and TypeScript SDK for Lettermint. It runs on Node.js 20+, Bun, Deno and edge runtimes, and has no dependencies.
Upgrading from 2.x? Read UPGRADE.md.
Installation
npm install lettermint
Quick start
Create a client with a project sending token and send an email:
import { Lettermint } from 'lettermint';
const lettermint = new Lettermint({ sendingToken: process.env.LETTERMINT_PROJECT_TOKEN });
const result = await lettermint.emails.send({
from: 'Acme <hello@acme.com>',
to: ['jane@example.com'],
subject: 'Welcome to Acme',
html: '<p>Thanks for signing up.</p>',
text: 'Thanks for signing up.',
});
console.log(result.message_id, result.status); // "…", "pending"
import Lettermint from 'lettermint' and const { Lettermint } = require('lettermint') work as well.
Tokens
Lettermint has two kinds of API tokens:
| Option |
Token |
Used by |
Sent as |
sendingToken |
Project sending token (lm_…) |
lettermint.emails.* |
x-lettermint-token header |
teamToken |
Team API token (lm_team_…) |
Every other part (domains, messages, projects, …) |
Authorization: Bearer header |
Pass one or both:
const lettermint = new Lettermint({
sendingToken: process.env.LETTERMINT_PROJECT_TOKEN,
teamToken: process.env.LETTERMINT_TEAM_TOKEN,
});
Each part uses its own token and never falls back to the other one. If the token a method needs is missing, it throws a LettermintConfigError that names the option (domains.list needsteamToken``), before any request. lettermint.ping() uses the team token when it is set, otherwise the sending token. messages.reschedule(), messages.cancel() and messages.resend() accept either token in the same way.
You can also pass a single token as a string. The SDK chooses its type by the format: lm_team_ followed by letters and digits is a team token, and lm_ followed by letters and digits is a sending token. Any other value, such as an SSO verification token (lm_sso_…), throws a LettermintConfigError; pass { sendingToken } or { teamToken } explicitly in that case.
const lettermint = new Lettermint(process.env.LETTERMINT_TOKEN!);
// Other options go in the second argument:
const withTimeout = new Lettermint(process.env.LETTERMINT_TOKEN!, { timeout: 10_000 });
Other formats throw LettermintConfigError. Use { sendingToken } or { teamToken } for them. Error messages never contain the token.
Options
| Option |
Default |
Description |
sendingToken |
|
Project sending token. |
teamToken |
|
Team API token. |
baseUrl |
https://api.lettermint.co/v1 |
API base URL. |
timeout |
30000 |
Request timeout in milliseconds. It covers the response headers and the body. |
fetch |
global fetch |
A fetch implementation, for example for tests or a proxy. |
The client holds no per-request state, so create it once and share it.
Sending email
The email builder
emails.compose() returns an immutable builder. Every setter returns a new builder and leaves the original unchanged, so you can keep a base builder and reuse it, also across concurrent requests:
const welcome = lettermint.emails
.compose()
.from('Acme <hello@acme.com>')
.subject('Welcome to Acme')
.tags([{ name: 'campaign', value: 'welcome' }]);
await welcome.to('jane@example.com').html('<p>Hi Jane</p>').send();
await welcome.to('john@example.com').html('<p>Hi John</p>').send();
When you build an email over several statements, keep the returned builder:
let email = lettermint.emails.compose().from('hello@acme.com').to(user.email).subject('Your invoice');
if (user.accountant) email = email.cc(user.accountant);
await email.html(invoiceHtml).send();
Builder methods:
| Method |
Description |
from(address) |
Sender, for example Acme <hello@acme.com>. |
to(...addresses), cc(...), bcc(...), replyTo(...) |
Replace the recipient list. |
subject(text) |
Subject line. |
html(html \| null), text(text \| null) |
Bodies. null removes one. |
headers(record) |
Custom email headers. |
metadata(record) |
Data stored with the message, not added as headers. |
tags([{ name, value }]), tag(name \| null) |
Name/value tags, and the legacy single tag. |
route(slug) |
The route to send through. |
scheduledAt(when \| null) |
Delivery time: a Date, ISO 8601, or English such as tomorrow 9am. |
settings({ track_opens, track_clicks, tls }) |
Per-email settings that override the route. |
sandboxResult(result) |
The result a Sandbox project simulates. |
attach({ filename, content, contentType?, contentId? }) |
Adds an attachment. |
send(options?) |
Sends a snapshot of the email. The builder can be sent again. |
build() |
Returns the message in API format. |
emails.compose(message) starts a builder from an existing message.
Plain objects
emails.send() takes the message in the API's format (reply_to, scheduled_at, sandbox_result, …). It is typed as EmailMessage:
await lettermint.emails.send({
from: 'Acme <hello@acme.com>',
to: ['jane@example.com'],
reply_to: ['support@acme.com'],
subject: 'Your order has shipped',
html,
metadata: { order_id: '1234' },
});
Batch sending
Send up to 500 emails in one request. The array may mix messages and builders:
const results = await lettermint.emails.sendBatch([
{ from: 'hello@acme.com', to: ['jane@example.com'], subject: 'Hi Jane', text: 'Hello' },
welcome.to('john@example.com').html('<p>Hi John</p>'),
]);
Give each email an idempotency_key to retry a batch safely. A retry returns the original result of every email that was already accepted and sends only the rest. Keys must be unique within the batch. Reusing a key with different content throws a ConflictError and sends nothing. For a builder, spread its build() output:
await lettermint.emails.sendBatch([
{ ...invoice, idempotency_key: `invoice-${invoice.id}` },
{ ...welcome.to('john@example.com').build(), idempotency_key: 'welcome-john' },
]);
Emails are accepted in order. If one fails, the emails before it may already be accepted; the thrown ApiError lists them in error.details.accepted ({ index, message_id } per email).
Idempotency
Pass an idempotency key to make retries safe. The API processes a key once, so a retry with the same key does not send the email again. The key applies only to the call it is passed to. For per-email keys in a batch, see Batch sending.
await lettermint.emails.send(message, { idempotencyKey: `order-${order.id}-confirmation` });
await builder.send({ idempotencyKey: 'welcome-jane' });
await lettermint.emails.sendBatch(messages, { idempotencyKey: 'newsletter-2026-10' });
The SDK never retries on its own.
Scheduling
const result = await lettermint.emails
.compose()
.from('hello@acme.com')
.to('jane@example.com')
.subject('Your trial ends tomorrow')
.text('…')
.scheduledAt(new Date(Date.now() + 24 * 60 * 60 * 1000))
.send();
if (result.status === 'scheduled') console.log(result.scheduled_at);
await lettermint.messages.reschedule(result.message_id, { scheduled_at: '2026-10-20T09:00:00Z' });
await lettermint.messages.cancel(result.message_id);
Sandbox
In a Sandbox project, nothing is delivered. Choose the simulated result per email:
const result = await lettermint.emails.compose()
.from('hello@acme.com')
.to('jane@example.com')
.subject('Test')
.text('Test')
.sandboxResult('hard_bounced')
.send();
console.log(result.sandbox, result.sandbox_result); // true, "hard_bounced"
Tags
tags() accepts up to 20 case-sensitive name/value tags (19 when the legacy tag() is also set). Names match ^[A-Za-z0-9_-]{1,32}$, may not start with __lettermint and must be unique. Values match ^[A-Za-z0-9_-]{1,64}$. The SDK checks this before the request and throws LettermintValidationError. Because builders are immutable, a rejected tag leaves the builder unchanged.
const email = base.tags([
{ name: 'campaign', value: 'welcome' },
{ name: 'plan', value: 'pro' },
]);
Attachments
content is a base64 string, a Uint8Array (including a Node.js Buffer) or an ArrayBuffer. The SDK encodes bytes to base64.
import { readFile } from 'node:fs/promises';
await lettermint.emails
.compose()
.from('billing@acme.com')
.to('jane@example.com')
.subject('Your invoice')
.html('<img src="cid:logo"> Your invoice is attached.')
.attach({ filename: 'invoice.pdf', content: await readFile('invoice.pdf'), contentType: 'application/pdf' })
.attach({ filename: 'logo.png', content: logoBase64, contentId: 'logo' })
.send();
lettermint.blockedFileTypes() lists the extensions and MIME types the API rejects.
Team API
With a team token, the client manages domains, messages, projects, routes, statistics, suppressions, the team and webhooks:
const lettermint = new Lettermint({ teamToken: process.env.LETTERMINT_TEAM_TOKEN });
const domain = await lettermint.domains.create({ domain: 'acme.com' });
await lettermint.domains.verifyDnsRecords(domain.id);
// Move a domain with a DKIM TXT record to managed DKIM: add the two new CNAME records from the
// response, then activate when `dkim_transition.state` is `ready_to_activate`.
const upgrade = await lettermint.domains.startDkimUpgrade(domain.id);
console.log(upgrade.data.dkim_transition); // { type: 'legacy_upgrade', state: 'awaiting_dns', ... }
await lettermint.domains.activateDkimUpgrade(domain.id);
// Replace a managed DKIM key early; the CNAME records stay the same.
await lettermint.domains.rotateDkimKey(domain.id);
const project = await lettermint.projects.create({ name: 'Production' });
console.log(project.api_token); // the new project's sending token, shown once
// Create another sending token for the project. Its value is only returned once: store it now.
// Use it to send through the API, or as the SMTP password when SMTP is enabled (see `created.smtp`).
const created = await lettermint.projects.apiTokens.create(project.id, { name: 'Checkout service' });
console.log(created.data.token);
await lettermint.projects.apiTokens.delete(project.id, created.data.id);
// Use your own domain for open and click tracking links: add a CNAME record that points to
// `cname_target`, then check it. A failed check throws a ValidationError whose `body` holds the outcome.
const tracking = await lettermint.projects.trackingDomain.update(project.id, { domain: 'track.acme.com' });
console.log(tracking.data.cname_target);
await lettermint.projects.trackingDomain.verify(project.id);
// Inbound route settings: hold messages with malware in quarantine (the default), and refuse messages
// that no inbound rule matches during SMTP (`spam_filter`, the default, lets the spam threshold decide).
await lettermint.routes.update('route-id', {
inbound_quarantine_malware: true,
inbound_unmatched_action: 'reject',
});
// Inbound rules: the first rule that matches the From address decides. A domain also covers its
// subdomains; `allow` skips the spam threshold only for senders that pass DMARC, or aligned DKIM or SPF.
const rule = await lettermint.routes.inboundRules.create('route-id', {
action: 'allow',
senders: ['partner.com', 'billing@vendor.com'],
position: 1, // leave out to add the rule below the other rules
});
await lettermint.routes.inboundRules.update('route-id', rule.data.id, { action: 'quarantine' });
const { data: rules } = await lettermint.routes.inboundRules.list('route-id');
await lettermint.routes.inboundRules.delete('route-id', rule.data.id);
const message = await lettermint.messages.retrieve('message-id');
console.log(message.malware?.signatures); // only set when the scanner found malware
const stats = await lettermint.stats.retrieve({ from: '2026-10-01', to: '2026-10-31' });
console.log(stats.totals.complaint_rate); // spam complaints per delivered email (0.002 is 0.2%), or null
const html = await lettermint.messages.html('message-id');
// Send a sent message again as a new message; leave out the body for every original recipient.
const resent = await lettermint.messages.resend('message-id', { recipients: ['jane@example.com'] });
// Send a webhook delivery's original payload again now; automatic retries continue if it fails.
await lettermint.webhooks.deliveries.retry('webhook-id', 'delivery-id');
// Invite a person to the team; the API sends the invitation email.
const invite = await lettermint.team.invites.create({
email: 'jane@example.com',
role_id: 'role-id',
project_access: { scope: 'selected', project_ids: [project.id] },
});
// Create a custom role; delete it later and move its assignments to another role.
const role = await lettermint.team.createRole({ name: 'Support', permissions: ['members:read'] });
await lettermint.team.deleteRole(role.id, { replacement_role_id: 'other-role-id' });
// The members who can access a project (with access to all projects or selected for it).
const members = await lettermint.team.members.list({ filter: { project_id: project.id } });
await lettermint.team.members.remove('user-id');
// Create a team token with fewer abilities. It can only have abilities that this token has, copies
// this token's IP allowlist and can't outlive it. Its value is only returned once: store it now.
const teamToken = await lettermint.team.apiTokens.create({
name: 'Deploys',
abilities: ['read:domains'],
expires_at: '2027-01-01T00:00:00Z',
});
console.log(teamToken.data.token);
// Rename it or replace its abilities. `abilities` replaces the whole list; this token must have each one.
await lettermint.team.apiTokens.update(teamToken.data.id, { abilities: ['read:domains', 'read:messages'] });
await lettermint.team.apiTokens.delete(teamToken.data.id);