TypeScript and JavaScript

TypeScript and JavaScript

The Mailset Node.js SDK for TypeScript and JavaScript: install it, send email, verify webhooks, handle errors.

  • Every public command238 commands, each a typed method
  • No dependenciesNothing else to install beside it
  • 30 KBThe whole SDK, minified, as one ES module
  • Typed throughoutTypes for every command and answer
  • Retries built inTwo more tries, and a send never doubles
  • Timeouts per try30 seconds a try, then tried again
On this page
  1. Requirements
  2. Install
  3. Create a client
  4. Send
  5. Send many
  6. Promotional email
  7. Idempotency
  8. Check the key
  9. Delivery search
  10. Webhooks
  11. Errors
  12. Build the message yourself
  13. Types
  14. Version and licence

Requirements

Runs onNode.js 20+testedBun 1.4+testedDeno 2.9+testedCloudflare Workerstested

Your key is a secret, so the SDK runs on a server or a worker, never in a page a browser loads.

Install

Add the SDK to your project.

Plain JavaScript uses the same package, with the same import.

JavaScript
import { Mailset } from 'mailset';
npm install mailset

Create a client

One client holds one MAILSET_KEY. Make it when your server starts and use it for every call.

new Mailset(options?: MailsetOptions): Mailset

A client for one credential: MAILSET_KEY or MAILSET_TOKEN, given or read from the environment. Nothing is sent until you call a method.

Parameters

options?: MailsetOptions

  • keystringoptional

    MAILSET_KEY (msk1_…), an app key: sends as the mailboxes its grant names. An API token (mst_…) works here too.

  • tokenstringoptional

    MAILSET_TOKEN (mst_…), an API token: a person's, for the commands no app key can run, such as domains.add.

  • baseUrlstringoptional

    Where Mailset is. A key names its own; a token goes to https://mailset.app. MAILSET_API in the environment overrides both.

  • orgstringoptional

    The org a command is about, for a person in more than one. Each call may name another.

  • timeoutnumberoptional

    How long one try of a call may take, in ms. 30 seconds unless told. A try that runs out is tried again like a network failure.

  • maxRetriesnumberoptional

    How many times a call is tried again after a network failure, a timeout or a 5xx, waiting longer each time (or as Retry-After says). 2 unless told; 0 never. A send is safe to try again: each try carries the same bytes and Message-ID, so Mailset never sends it twice.

  • onApproval(approval: Approval) => void | Promise<void>optional

    Called when a command needs a passkey: open approval.url (or send it to whoever approves), and the call goes on once they do. Without it, such a command throws step_up_required with the purpose to approve.

  • fetch(url: string, init: RequestInit) => Promise<Response>optional

    Your own fetch, for tests or a proxy.

  • now() => numberoptional

    The clock every call is signed with, in ms. Only tests change it.

Returns

Mailset

A client for one credential: MAILSET_KEY or MAILSET_TOKEN, given or read from the environment. Nothing is sent until you call a method.

  • This client's MAILSET_KEY.

  • What became of the mail this key sent.

  • Events from your org's hook: the same object as the standalone webhooks.

  • campaignsobject

    Campaign mail, from a campaigns key: mailset.campaigns.submit.

    Show child attributesHide child attributes
    • submit(input: CampaignSubmitInput, options?: CallOptions) => Promise<CampaignSubmitted>

      Sends a campaign's messages, one per recipient, from a sending domain. Answers one result per message, in order: queued, or refused with why. It needs a campaigns key (mailset keys create --campaigns).

  • sendingobject

    One message from a sending domain: mailset.sending.submit.

    Show child attributesHide child attributes
    • submit(input: SendingSubmitInput, options?: CallOptions) => Promise<SendingSubmitted>

      Sends one message from a sending domain, the way a reply goes, never tracked. Answers each envelope address: queued or refused.

  • Approvals for commands that need a passkey.

    Show child attributesHide child attributes

    MailsetApprovals: Approvals for commands that need a passkey: mailset.approvals. Only an API token can ask for one, since a person approves it.

    • request(purpose: PasskeyPurpose) => Promise<Approval>

      Opens an approval for what a step_up_required error named.

    • wait(approval: Approval | string, options?: object) => Promise<string>

      Waits until it's approved, and answers the id to pass as approval. Throws forbidden when it's refused or expires.

  • sendfunction

    See Send and Send many.

  • request(command: string, input?: Record<string, unknown>, options?: CallOptions) => Promise<unknown>

    Any command by its id, with its input as Mailset takes it: for one this SDK has no method for yet. Answers its data.

Pass the key in

Where your app keeps its secrets elsewhere, hand the key to the client yourself. A token goes the same way.

Options

Everything has a default. Name a credential, an org, how long a try may take and how often a call is tried again, only where yours differ.

Authentication

TypeScript
import { Mailset } from 'mailset';

// One client for the whole server, from MAILSET_KEY
// in the environment. Nothing is sent until you
// call send.
export const mailset = new Mailset();
Pass the key in
import { Mailset } from 'mailset';

// From your secret store or config, never in the code.
// Or { token } with an API token.
const mailset = new Mailset({ key: config.mailsetKey });
Options
import { Mailset } from 'mailset';

const mailset = new Mailset({
	// Or `token` with an API token (MAILSET_TOKEN).
	key: process.env.MAILSET_KEY,
	// For a person in more than one org: which one.
	org: 'org_7c2e9a4f',
	// Each try may take 10 seconds. A network failure
	// or a 5xx is tried 3 more times, waiting longer.
	timeout: 10_000,
	maxRetries: 3,
	// A command that needs a passkey waits for it.
	onApproval: (approval) => {
		console.log(`Approve it: ${approval.url}`);
	},
});

console.log(await mailset.key.check());

Send

Send one message and get its receipt. A message Mailset refuses is an error with a code, never a silent drop.

mailset.send(input: SendInput): Promise<Sent>

One message: its receipt, or a MailsetError thrown when Mailset refuses it. Many messages: one result each, in the same order, with ok saying which went. A refusal is that message's error and never stops the rest. It throws only when the key is refused, Mailset can't be reached before anything was taken, or two messages of the array carry the same idempotencyKey from the same address (invalid_input, before anything is sent). Any number goes: past 100, or 48 MB, they go in several calls. Mail to an Apple Hide My Email address or a temporary inbox, and promotional mail to someone who unsubscribed from its mailbox, isn't refused: the receipt's skipped names each one, and it goes to everyone else.

Parameters

input: SendInput

  • fromAddressrequired

    An address this key may send as: its mailbox or one of that mailbox's aliases, or for a domain key one of the addresses it names (any address on its domain, made with --any-address).

    Show child attributesHide child attributes

    Address: moc.elpmaxe@ana, Ana <moc.elpmaxe@ana>, or the two parts.

    • namestring | nulloptional
    • emailstringrequired
  • toAddress | Address[]required
    Show child attributesHide child attributes

    Address: moc.elpmaxe@ana, Ana <moc.elpmaxe@ana>, or the two parts.

    • namestring | nulloptional
    • emailstringrequired
  • ccAddress | Address[]optional
    Show child attributesHide child attributes

    Address: moc.elpmaxe@ana, Ana <moc.elpmaxe@ana>, or the two parts.

    • namestring | nulloptional
    • emailstringrequired
  • bccAddress | Address[]optional

    Never shown to anyone: Mailset takes it out before the message leaves.

    Show child attributesHide child attributes

    Address: moc.elpmaxe@ana, Ana <moc.elpmaxe@ana>, or the two parts.

    • namestring | nulloptional
    • emailstringrequired
  • replyToAddress | Address[]optional
    Show child attributesHide child attributes

    Address: moc.elpmaxe@ana, Ana <moc.elpmaxe@ana>, or the two parts.

    • namestring | nulloptional
    • emailstringrequired
  • subjectstringrequired
  • textstringrequired
  • htmlstringoptional

    A designed version. Without it, the text is wrapped in plain HTML.

  • attachmentsAttachment[]optional
    Show child attributesHide child attributes

    Attachment: A file to send with a message: its name, its type, and its bytes or their base64.

    • filenamestringrequired
    • contentTypestringoptional

      Defaults to application/octet-stream.

    • contentUint8Array | ArrayBufferrequired

      Give this or base64.

    • base64stringrequired

      Give this or content.

  • headersRecord<string, string>optional

    Extra headers, such as your own List-Unsubscribe. Addressing, subject, dates and MIME headers are Mailset's and can't be set here.

  • modeenumoptional

    transactional (the default): a sign-in code, a receipt, an alert, a digest someone turned on in your settings (link to those settings in the footer). It needs no unsubscribe, and can't carry List-Unsubscribe or Precedence: bulk.

    promotional: a newsletter, an offer. It goes to one address in to, with no cc or bcc, and needs no List-Unsubscribe from you: Mailset adds a one-click one and honors it. Write {{mailset_unsubscribe}} where the link goes, in text and as a link's href in html. A part without it gets a last line, "Unsubscribe" with the link. Once someone uses it, promotional mail from that mailbox (for a domain key, from that domain) to them is skipped (Sent.skipped, reason unsubscribed), your hook hears unsubscribed, and transactional mail still reaches them.

    Your own header still wins. Pass List-Unsubscribe: <https://…> and List-Unsubscribe-Post: List-Unsubscribe=One-Click in headers, with the same URL in both text and html, and Mailset adds nothing: honoring those opt-outs is then yours.

    One oftransactionalpromotional

  • keepCopybooleanoptional

    Keep a copy in the mailbox's Sent folder, like mail a person writes. Off by default: a product's mail leaves only its delivery log. With a mode, it is a product's mail and nothing is kept. A domain key has no mailbox to keep it in, so it refuses keepCopy.

  • deliverByDate | stringoptional

    The latest it may go out: a Date, or a time from now such as '30s', '10m' or '2h'. Use it on sign-in codes and anything else that's useless late. Mail a limit would hold past it is refused at once (limit_reached, with retryAt), and mail still waiting when it comes is dropped, never sent, and shows as expired in the delivery log.

  • idempotencyKeystringoptional

    A name of your own for this one send, such as receipt-8842, so sending it again can't send it twice. After a timeout or a crash, call send again with the same key: Mailset answers the first send's receipt, the same id and messageId, and sends nothing new. 1 to 255 characters, no line breaks.

    A key belongs to its from address and has no time limit. Only the key is compared, never the content, so the same key with other words or another recipient sends nothing: the first one wins. A send that never went (refused when you sent it, or later failed or expired) doesn't count, so the same key sends it again.

    In an array, each key is used once. The same key on two messages from the same address throws invalid_input before anything is sent, and the message names the key and where the items are.

Returns

Promise<Sent>

Mailset took the message.

  • oktrue
  • idstring

    Mailset's id for this send.

  • messageIdstring

    The Message-ID header, without its angle brackets.

  • statusenum

    sent: it went. queued: Mailset holds it and sends it at sendsAt, because a sending limit needs time to make room or the provider stumbled. Nothing to do either way.

    One ofsentqueued

  • stateenum

    The same as status.

    One ofsentqueued

  • sendsAtnumberoptional

    When a queued message should go out, in ms.

  • reasonstringoptional

    Why a queued message waits, in words for people.

  • skippedSkipped[]optional

    Recipients Mailset skipped: they never get it, the others do. Nothing to retry, and it costs no brake. When it names every recipient, nothing went out, so ask the person for another address. Absent when nobody was skipped.

    Show child attributesHide child attributes

    Skipped: An address Mailset left out of a message, and why. private_relay: Apple's Hide My Email (@privaterelay.appleid.com), which refuses mail from senders your app never registered with Apple. disposable: a temporary inbox, like mailinator.com, that nobody reads. unsubscribed: they used Mailset's unsubscribe link in this mailbox's promotional mail (for a domain key, this domain's), so its promotional mail no longer goes to them.

    • addressstring
    • reasonenum

      One ofprivate_relaydisposableunsubscribed

Give sign-in codes a deadlineHonor unsubscribes and complaintsHandle skipped recipientsGuide for Node.js

TypeScript
import { Mailset } from 'mailset';

// Reads MAILSET_KEY from the environment.
const mailset = new Mailset();

const sent = await mailset.send({
	from: 'Acme <moc.elpmaxe@olleh>',
	to: 'gro.elpmaxe@ana',
	subject: 'Your Acme code',
	text: 'Your code is 123456.',
	html: '<p>Your code is <b>123456</b>.</p>',
	deliverBy: '10m',
});

console.log(sent.id, sent.status);
Returns
{
  "ok": true,
  "id": "out_3f9a1c0e7b2d",
  "messageId": "moc.elpmaxe@85a4d2b7e0c1a9f3",
  "status": "sent",
  "state": "sent"
}

Send many

Send several messages in one call and get one result per message, in the same order. A refused message never stops the rest.

mailset.send(inputs: SendInput[]): Promise<SendResult[]>

Parameters

Returns

Promise<SendResult[]>

One message's answer from send([...]).

  • SentSent

    Mailset took the message.

  • NotSentobject

    Mailset refused this one message of a batch. The rest are unaffected.

    Show child attributesHide child attributes
    • okfalse
    • messageIdstring | null

      Null when the message couldn't even be built.

Send many messages at once

TypeScript
import { Mailset } from 'mailset';

// Reads MAILSET_KEY from the environment.
const mailset = new Mailset();

const results = await mailset.send([
	{
		from: 'Acme <moc.elpmaxe@olleh>',
		to: 'gro.elpmaxe@ana',
		subject: 'Your invoice',
		text: 'Invoice 8842 is ready.',
	},
	{
		from: 'Acme <moc.elpmaxe@olleh>',
		to: 'gro.elpmaxe@neb',
		subject: 'Your invoice',
		text: 'Invoice 8843 is ready.',
	},
]);

for (const result of results) {
	if (result.ok) console.log(result.id, result.status);
	else console.error(result.messageId, result.error.code);
}
Returns
[
  {
    "ok": true,
    "id": "out_3f9a1c0e7b2d",
    "messageId": "moc.elpmaxe@85a4d2b7e0c1a9f3",
    "status": "sent",
    "state": "sent"
  },
  {
    "ok": false,
    "messageId": "moc.elpmaxe@f1b5x7q9p1m4k2d8",
    "error": {
      "code": "forbidden",
      "message": "This app can’t send as that address.",
      "refusal": null,
      "retryAt": null
    }
  }
]

Promotional email

Send a newsletter or an offer with mode: 'promotional'. {{mailset_unsubscribe}} is a placeholder Mailset fills in for each message, with a signed one-click unsubscribe link unique to that recipient and that message. You never generate the link, and Mailset adds the matching List-Unsubscribe and List-Unsubscribe-Post headers itself.

transactional (the default): a sign-in code, a receipt, an alert, a digest someone turned on in your settings (link to those settings in the footer). It needs no unsubscribe, and can't carry List-Unsubscribe or Precedence: bulk.

promotional: a newsletter, an offer. It goes to one address in to, with no cc or bcc, and needs no List-Unsubscribe from you: Mailset adds a one-click one and honors it. Write {{mailset_unsubscribe}} where the link goes, in text and as a link's href in html. A part without it gets a last line, "Unsubscribe" with the link. Once someone uses it, promotional mail from that mailbox (for a domain key, from that domain) to them is skipped (Sent.skipped, reason unsubscribed), your hook hears unsubscribed, and transactional mail still reaches them.

Your own header still wins. Pass List-Unsubscribe: <https://…> and List-Unsubscribe-Post: List-Unsubscribe=One-Click in headers, with the same URL in both text and html, and Mailset adds nothing: honoring those opt-outs is then yours.

Honor unsubscribes and complaintsHandle skipped recipients

TypeScript
import { Mailset } from 'mailset';

// Reads MAILSET_KEY from the environment.
const mailset = new Mailset();

const text = [
	'Three new things this month.',
	'',
	'Leave this list: {{mailset_unsubscribe}}',
].join('\n');

const html = [
	'<p>Three new things this month.</p>',
	'<a href="{{mailset_unsubscribe}}">Leave this list</a>',
].join('\n');

const sent = await mailset.send({
	from: 'Acme News <moc.elpmaxe.swen@swen>',
	to: 'gro.elpmaxe@ana',
	subject: 'What shipped in March',
	text,
	html,
	mode: 'promotional',
});

console.log(sent.id, sent.skipped);
What Ana receives
Headers Mailset adds
List-Unsubscribe: <https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc>
List-Unsubscribe-Post: List-Unsubscribe=One-Click
Text part
Three new things this month.

Leave this list: https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc
HTML part

Three new things this month.

Leave this list

A sample link. Mailset makes a new one for every message.

What Ana receives without the placeholder
Text part
Three new things this month.

Unsubscribe: https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc
HTML part

Three new things this month.

Unsubscribe

Mailset adds the last line of each part. The headers are the same.

Idempotency

Name a send with idempotencyKey, and sending it again after a timeout or a crash can’t send it twice.

A name of your own for this one send, such as receipt-8842, so sending it again can't send it twice. After a timeout or a crash, call send again with the same key: Mailset answers the first send's receipt, the same id and messageId, and sends nothing new. 1 to 255 characters, no line breaks.

A key belongs to its from address and has no time limit. Only the key is compared, never the content, so the same key with other words or another recipient sends nothing: the first one wins. A send that never went (refused when you sent it, or later failed or expired) doesn't count, so the same key sends it again.

In an array, each key is used once. The same key on two messages from the same address throws invalid_input before anything is sent, and the message names the key and where the items are.

Retry without sending twice

TypeScript
import { Mailset, type SendInput } from 'mailset';

// Reads MAILSET_KEY from the environment.
const mailset = new Mailset();

const receipt: SendInput = {
	from: 'Acme <moc.elpmaxe@olleh>',
	to: 'gro.elpmaxe@ana',
	subject: 'Your receipt',
	text: 'Thanks for your order.',
	idempotencyKey: 'receipt-8842',
};

const first = await mailset.send(receipt);
// After a timeout or a crash, send it again.
// The same key answers the first receipt,
// and nothing goes out twice.
const again = await mailset.send(receipt);

console.log(first.id === again.id);
Returns
{
  "ok": true,
  "id": "out_3f9a1c0e7b2d",
  "messageId": "moc.elpmaxe@85a4d2b7e0c1a9f3",
  "status": "sent",
  "state": "sent"
}

Check the key

Ask what the key may do now. Call it when your server starts and once a day: each call keeps the key alive.

mailset.key.check(): Promise<KeyStatus>

Proves the key still works and keeps it alive: a key unused for 90 days stops. Call it when your server starts and once a day, so a product that sends rarely never loses its key, and a revoked one shows up in your logs before a customer misses an email.

Returns

Promise<KeyStatus>

What this key may do now. Each call also keeps it alive: see check.

  • namestring

    The app's name, as approved.

  • expiresAtnumber

    When the key stops working, in ms. Every call moves it 90 days out.

  • pausedstring | null

    Why Mailset stopped this app's mail (too many bounces or complaints), or null.

  • mailboxesarray of objects

    A mailbox key's mailbox. Empty for a domain key.

    Show child attributesHide child attributes
    • addressstring
    • accessarray of enums

      One ofreadsend

    • sendAsstring[]

      The addresses it may send as: the mailbox and its aliases.

    • sendingstring

      ready: its domain can send.

  • domainsarray of objects

    A domain key's sending-only domain, with no mailbox, and what it sends as there. Empty for a mailbox key, and from a server older than domain keys.

    Show child attributesHide child attributes
    • namestring

      example.com. Its subdomains aren't covered.

    • sendingstring

      ready: it can send.

    • fromstring[] | null

      The From addresses it sends as, the only ones. Null: any address on the domain, a key made with --any-address, and from a server older than this field.

Keep a key alive

TypeScript
import { Mailset } from 'mailset';

// Reads MAILSET_KEY from the environment.
const mailset = new Mailset();

// When the server starts, and once a day.
const status = await mailset.key.check();

if (status.paused) console.warn('Paused:', status.paused);
console.log('Works until', new Date(status.expiresAt));
// A mailbox key sends as its mailbox.
for (const { address, sending } of status.mailboxes)
	if (sending !== 'ready') console.warn(address, sending);
// A domain key sends as the addresses it names.
for (const { name, sending, from } of status.domains) {
	const as = from?.join(', ') ?? 'any address';
	console.log(name, 'sends as', as);
	if (sending !== 'ready') console.warn(name, sending);
}
Returns
{
  "name": "Acme API",
  "expiresAt": 1803824940000,
  "paused": null,
  "mailboxes": [
    {
      "address": "moc.elpmaxe@olleh",
      "access": [
        "send"
      ],
      "sendAs": [
        "moc.elpmaxe@olleh"
      ],
      "sending": "ready"
    }
  ],
  "domains": []
}

Delivery search

Look up what became of the mail this key sent, one line per recipient. For a support question or a nightly check.

mailset.delivery.search(input?: DeliverySearchInput, options?: CallOptions): Promise<DeliveryPage>

Finds what became of the mail this key sent, one line per recipient, newest first. A key sees only what left the mailbox it sends as, or for a domain key the addresses it sends as, so a search by recipient answers "did Ana get her receipt?" and nothing about anyone else's mail. It needs a key that can send, and throws MailsetError when the key is refused or Mailset can't be reached. For each change as it happens, use the hook instead: see webhooks.

Parameters

  • inputDeliverySearchInputoptional
    Show child attributesHide child attributes

    DeliverySearchInput: Which lines of the delivery log to find. Every field narrows the search; with none, you get the newest.

    • idstringoptional

      Only the lines of one send: the id its receipt answered.

    • messageIdstringoptional

      Only the lines of the message with this Message-ID, the messageId its receipt answered.

    • recipientstringoptional

      A recipient's whole address, or part of one, such as @example.org.

    • senderstringoptional

      One of the addresses this key sends as, or part of one.

    • statusDeliveryStatusoptional

      Only lines with this status.

      One ofsentdelivereddelayedbouncedcomplainedrejectedexpiredskipped

    • sinceDate | number | stringoptional

      From this moment on: a Date, a time in ms, or a day as '2026-11-30', which counts from its start in UTC.

    • untilDate | number | stringoptional

      Up to this moment, written like since. A day counts to its end in UTC.

    • limitnumberoptional

      How many lines a page holds, 1 to 200. 50 unless told.

    • cursorstringoptional

      The next of the page before, for the page after it.

  • optionsCallOptionsoptional
    Show child attributesHide child attributes

    CallOptions: What every command method takes beside its input.

    • orgstringoptional

      The org this is about, by its id: for a person in more than one.

    • approvalstringoptional

      An approval's id, once someone approved it with their passkey: see approvals.

    • timeoutnumberoptional

      How long one try may take, in ms, for this call alone.

    • signalAbortSignaloptional

      Stops the call.

Returns

Promise<DeliveryPage>

One page of the delivery log, newest first.

  • Show child attributesHide child attributes

    DeliveryLine: One recipient's line in the delivery log: a message to three people has three. Addresses and outcomes only, never a subject or anything from the body.

    • idstring

      The line's id.

    • atnumber

      When it happened, in ms.

    • senderstring | null

      The mailbox it left from, whichever of its addresses was in From. For a domain key's mail, the address it went as.

    • recipientstring

      The address it went to.

    • One ofsentdelivereddelayedbouncedcomplainedrejectedexpiredskipped

    • reasonstring | null

      Why, in words for people, when the status needs saying why.

    • messagestringoptional

      The send this line is about: the id its receipt answered.

    • messageIdstringoptional

      Its Message-ID header, without the angle brackets: messageId from send.

    • clientDeliveryClient | null

      Which client sent it. Null when its request named none.

      Show child attributesHide child attributes

      DeliveryClient: Which client sent a message, from the Mailset-Client header its request carried: one of Mailset's SDKs by its language, cli, web, ios, or other. A name this version doesn't know yet still shows, as Mailset names it.

      • name'typescript' | 'python' | 'go' | 'ruby' | 'php' | 'java' | 'rust' | 'cli' | 'web' | 'ios' | 'other' | object
      • versionstring | null

        Its version, as it said. Null for other.

  • nextstring | null

    Pass it back as cursor for the next page. Null on the last one.

Handle bounces

TypeScript
import { Mailset } from 'mailset';

// Reads MAILSET_KEY from the environment.
const mailset = new Mailset();

// Did Ana get her receipt?
const { lines, next } = await mailset.delivery.search({
	recipient: 'gro.elpmaxe@ana',
	since: '2026-11-30',
});

for (const line of lines) {
	console.log(line.status, line.reason);
}
// Pass `next` back as `cursor` for the page after.
console.log(next);
Returns
{
  "lines": [
    {
      "id": "dlv_8d2k4m1p9q7x",
      "at": 1796048940000,
      "sender": "moc.elpmaxe@olleh",
      "recipient": "gro.elpmaxe@ana",
      "status": "bounced",
      "reason": "smtp; 550 5.1.1 The email account that you tried to reach does not exist.",
      "message": "out_3f9a1c0e7b2d",
      "messageId": "moc.elpmaxe@85a4d2b7e0c1a9f3",
      "client": {
        "name": "typescript",
        "version": "0.7.0"
      }
    }
  ],
  "next": null
}

Webhooks

Check that a request came from Mailset and read its events. It needs no key and no client, so a service that only receives events uses it alone.

webhooks.verify(request: WebhookRequest): Promise<MailEvent[]>

The events in a request from your hook, once its Mailset-Signature proves Mailset sent it with your secret in the last 5 minutes. Throws MailsetError: unauthorized for a missing or wrong signature, expired for an old one, invalid_input for a body that isn't events. Answer 2xx once you've kept them: Mailset sends a batch again, the same ids, until you do.

Parameters

request: WebhookRequest

  • bodystring | Uint8Array | ArrayBufferrequired

    The body exactly as it arrived, before any JSON parsing: the signature covers these bytes.

  • headersHeaders | Record<string, string | string[] | undefined>required

    The request's headers: a Headers, or Node's req.headers.

  • secretstringrequired

    The hook's signing secret, from mailset hooks set.

  • toleranceSecondsnumberoptional

    How old a signature may be, in seconds. 300 unless told.

  • nownumberoptional

    The clock, in ms. Only tests change it.

Returns

Promise<MailEvent[]>

One event from your org's hook. Switch on type; ignore a type you don't know yet.

  • QueuedEventobject

    A limit holds it, so it goes out later.

    Show child attributesHide child attributes
    • idstring

      Stable for this message, recipient and happening: dedupe on it.

    • atnumber

      When it happened, in ms.

    • messagestring

      Mailset's id for the message: the id that send answered.

    • messageIdstring

      Its Message-ID header, without the angle brackets: messageId from send.

    • recipientstring

      One recipient: a message to three people has three of each event.

    • appstring

      The app key that sent it, by the name it was approved with.

    • duplicateOfstringoptional

      Present when the same content went to this recipient from the same address less than 10 minutes before, under another Message-ID: the message of that earlier send. Both were sent. It most often means a retry without an idempotencyKey: give the send one and the second never goes.

    • type'queued'
    • sendsAtnumber

      When it should go out, in ms.

    • reasonstring
  • SentEventobject

    The provider took it.

    Show child attributesHide child attributes
    • idstring

      Stable for this message, recipient and happening: dedupe on it.

    • atnumber

      When it happened, in ms.

    • messagestring

      Mailset's id for the message: the id that send answered.

    • messageIdstring

      Its Message-ID header, without the angle brackets: messageId from send.

    • recipientstring

      One recipient: a message to three people has three of each event.

    • appstring

      The app key that sent it, by the name it was approved with.

    • duplicateOfstringoptional

      Present when the same content went to this recipient from the same address less than 10 minutes before, under another Message-ID: the message of that earlier send. Both were sent. It most often means a retry without an idempotencyKey: give the send one and the second never goes.

    • type'sent'
  • DeliveredEventobject

    The recipient's server took it.

    Show child attributesHide child attributes
    • idstring

      Stable for this message, recipient and happening: dedupe on it.

    • atnumber

      When it happened, in ms.

    • messagestring

      Mailset's id for the message: the id that send answered.

    • messageIdstring

      Its Message-ID header, without the angle brackets: messageId from send.

    • recipientstring

      One recipient: a message to three people has three of each event.

    • appstring

      The app key that sent it, by the name it was approved with.

    • duplicateOfstringoptional

      Present when the same content went to this recipient from the same address less than 10 minutes before, under another Message-ID: the message of that earlier send. Both were sent. It most often means a retry without an idempotencyKey: give the send one and the second never goes.

    • type'delivered'
  • BouncedEventobject

    It came back. hard won't change; soft may go on a later try.

    Show child attributesHide child attributes
    • idstring

      Stable for this message, recipient and happening: dedupe on it.

    • atnumber

      When it happened, in ms.

    • messagestring

      Mailset's id for the message: the id that send answered.

    • messageIdstring

      Its Message-ID header, without the angle brackets: messageId from send.

    • recipientstring

      One recipient: a message to three people has three of each event.

    • appstring

      The app key that sent it, by the name it was approved with.

    • duplicateOfstringoptional

      Present when the same content went to this recipient from the same address less than 10 minutes before, under another Message-ID: the message of that earlier send. Both were sent. It most often means a retry without an idempotencyKey: give the send one and the second never goes.

    • type'bounced'
    • bounceobject
      Show child attributesHide child attributes
      • kindenum

        One ofhardsoft

      • One ofmailboxdomainfulltoo_largepolicysuppressedother

      • reasonstring
  • ComplainedEventobject

    The recipient marked it as spam. Stop writing to them.

    Show child attributesHide child attributes
    • idstring

      Stable for this message, recipient and happening: dedupe on it.

    • atnumber

      When it happened, in ms.

    • messagestring

      Mailset's id for the message: the id that send answered.

    • messageIdstring

      Its Message-ID header, without the angle brackets: messageId from send.

    • recipientstring

      One recipient: a message to three people has three of each event.

    • appstring

      The app key that sent it, by the name it was approved with.

    • duplicateOfstringoptional

      Present when the same content went to this recipient from the same address less than 10 minutes before, under another Message-ID: the message of that earlier send. Both were sent. It most often means a retry without an idempotencyKey: give the send one and the second never goes.

    • type'complained'
  • FailedEventobject

    Mailset couldn't send it: the provider refused it, its app was paused, or five tries failed.

    Show child attributesHide child attributes
    • idstring

      Stable for this message, recipient and happening: dedupe on it.

    • atnumber

      When it happened, in ms.

    • messagestring

      Mailset's id for the message: the id that send answered.

    • messageIdstring

      Its Message-ID header, without the angle brackets: messageId from send.

    • recipientstring

      One recipient: a message to three people has three of each event.

    • appstring

      The app key that sent it, by the name it was approved with.

    • duplicateOfstringoptional

      Present when the same content went to this recipient from the same address less than 10 minutes before, under another Message-ID: the message of that earlier send. Both were sent. It most often means a retry without an idempotencyKey: give the send one and the second never goes.

    • type'failed'
    • reasonstring
  • ExpiredEventobject

    Its deliverBy came while it waited, so it never went.

    Show child attributesHide child attributes
    • idstring

      Stable for this message, recipient and happening: dedupe on it.

    • atnumber

      When it happened, in ms.

    • messagestring

      Mailset's id for the message: the id that send answered.

    • messageIdstring

      Its Message-ID header, without the angle brackets: messageId from send.

    • recipientstring

      One recipient: a message to three people has three of each event.

    • appstring

      The app key that sent it, by the name it was approved with.

    • duplicateOfstringoptional

      Present when the same content went to this recipient from the same address less than 10 minutes before, under another Message-ID: the message of that earlier send. Both were sent. It most often means a retry without an idempotencyKey: give the send one and the second never goes.

    • type'expired'
    • reasonstring
  • UnsubscribedEventobject

    Someone used Mailset's unsubscribe link in promotional mail this app sent. From now on promotional mail from that mailbox (or a domain key's domain) to them is skipped, so take them off your own list too. Transactional mail still reaches them.

    Show child attributesHide child attributes
    • type'unsubscribed'
    • idstring

      Stable for this opt-out. Someone let back in who leaves again has a new one.

    • atnumber

      When they unsubscribed, in ms.

    • recipientstring

      The address that unsubscribed, in lowercase.

    • appstringoptional

      The app key whose mail the link was in, by the name it was approved with.

    • messagestringoptional

      Mailset's id for the message the link was in: the id that send answered.

    • messageIdstringoptional

      That message's Message-ID header, without the angle brackets.

  • TestEventobject

    From mailset hooks test or the settings page: about no message.

    Show child attributesHide child attributes
    • type'test'
    • idstring
    • atnumber

Attributes

  • MailEventTypeMailEvent['type']

    Every event's type, as a union of the words.

In a web framework

The signature covers the body exactly as it arrived. Read the raw body before anything parses it, and hand that to the check: a body parsed as JSON and written out again no longer matches.

WebhooksHandle bouncesGuide for Next.jsGuide for ExpressGuide for NestJSGuide for Cloudflare Workers

TypeScript
import { MailsetError, webhooks } from 'mailset';

export async function POST(request: Request) {
	try {
		const events = await webhooks.verify({
			body: await request.text(),
			headers: request.headers,
			secret: process.env.MAILSET_HOOK_SECRET ?? '',
		});
		for (const event of events) {
			if (event.type !== 'bounced') continue;
			if (event.bounce.kind === 'hard')
				console.log('Stop writing to', event.recipient);
		}
		// 2xx once the events are kept.
		// Until then Mailset posts the batch again.
		return new Response(null, { status: 204 });
	} catch (error) {
		if (error instanceof MailsetError)
			return new Response(error.code, { status: 401 });
		throw error;
	}
}
In a web framework
// app/api/mailset/route.ts: a Next.js route handler.
import { MailsetError, webhooks } from 'mailset';

export async function POST(request: Request) {
	// The signature covers the body as it came, so read
	// it as text: request.json() would lose those bytes.
	const body = await request.text();
	try {
		const events = await webhooks.verify({
			body,
			headers: request.headers,
			secret: process.env.MAILSET_HOOK_SECRET ?? '',
		});
		for (const event of events) {
			if (event.type !== 'bounced') continue;
			if (event.bounce.kind === 'hard')
				console.log('Stop writing to', event.recipient);
		}
		return new Response(null, { status: 204 });
	} catch (error) {
		if (error instanceof MailsetError)
			return new Response(error.code, { status: 401 });
		throw error;
	}
}
Returns
[
  {
    "type": "bounced",
    "id": "evt_5b1f0c9a7e3d",
    "at": 1796048940000,
    "message": "out_3f9a1c0e7b2d",
    "messageId": "moc.elpmaxe@85a4d2b7e0c1a9f3",
    "recipient": "gro.elpmaxe@ana",
    "app": "Acme API",
    "bounce": {
      "kind": "hard",
      "class": "mailbox",
      "reason": "smtp; 550 5.1.1 The email account that you tried to reach does not exist."
    }
  }
]

Errors

Every refusal is one kind of error. Branch on its code, which never changes, and show its message to people.

Mailset refused, or couldn't be reached. code is stable; message is for people.

Attributes

  • codestring
  • refusalstring | null

    Why mail was refused, when it was. recipient: that address can't get mail (its domain takes none, or it bounced or reported spam before), so ask the person to check it. Others: domain_pending, domain_blocked, provider_refused. An Apple Hide My Email address, a temporary inbox or someone who unsubscribed is never a refusal: see Sent.skipped.

  • retryAtnumber | null

    On limit_reached for mail with a deliverBy: the soonest it could go, in ms. Send it again then, or with a later deliverBy.

  • statusnumber | null

    The HTTP status Mailset answered with, or null when it didn't answer.

  • timedOutboolean

    True when the last try ran out of its timeout before Mailset answered. code is then unavailable, as for a network failure.

  • On invalid_input: each field that was wrong, and what's wrong with it.

    Show child attributesHide child attributes

    MailsetErrorIssue: One wrong field of an invalid_input.

    • path(string | number)[]

      Which input field: its name, then any keys inside it.

    • messagestring
  • purposePasskeyPurpose | null

    On step_up_required: what a passkey has to approve. See approvals.

    Show child attributesHide child attributes

    PasskeyPurpose: What a passkey has to approve, as a step_up_required error names it.

    • kindstring

      What it's about: a domain, a mailbox, a member and so on.

    • idstring

      The action itself.

    • orgstring | null

      The org it's in, or null for a person's own account.

  • commandstring | null

    The command that was refused, by its id, when it was one.

  • needsstring | null

    When this credential can't run the command: the one that can, MAILSET_TOKEN or MAILSET_KEY, with the grant it needs.

  • docsstring

    Where the docs say what this code means and what to do.

  • helpstring

    The docs' link and where to ask, in one line: what a log should keep beside message.

Retries and timeouts

A network failure or a 5xx answer is tried again, twice unless you set maxRetries, waiting longer each time. One try may take 30 seconds unless you set timeout. A refusal is never tried again: the same request gets the same answer.

Errors and limits

TypeScript
import { Mailset, MailsetError } from 'mailset';

// Reads MAILSET_KEY from the environment.
const mailset = new Mailset();

try {
	await mailset.send({
		from: 'Acme <moc.elpmaxe@olleh>',
		to: 'gro.elpmaxe@ana',
		subject: 'Your Acme code',
		text: 'Your code is 123456.',
		deliverBy: '10m',
	});
} catch (error) {
	if (!(error instanceof MailsetError)) throw error;
	if (error.code === 'limit_reached' && error.retryAt)
		console.log('Try at', new Date(error.retryAt));
	else if (error.refusal === 'recipient')
		console.log('Ask them to check their address.');
	else console.error(error.code, error.message);
}
Returns
{
  "code": "limit_reached",
  "message": "The day’s sending limit is reached.",
  "refusal": null,
  "retryAt": 1796052540000
}

Build the message yourself

Get the message a send would build, without sending it: for a queue of your own, or a call to the API from another service.

messageOf(input: SendInput, now?: Date, id?: string): object

The whole message, as Mailset's messages.submit takes it. Its Message-ID is random unless one is given: send gives the one an idempotencyKey stands for.

Parameters

  • inputSendInputrequired
  • nowDateoptional

    Default new Date().

  • idstringoptional

Returns

object

  • rawstring
  • messageIdstring

messages.submit

TypeScript
import { messageOf } from 'mailset';

const { raw, messageId } = messageOf({
	from: 'Acme <moc.elpmaxe@olleh>',
	to: 'gro.elpmaxe@ana',
	subject: 'Your Acme code',
	text: 'Your code is 123456.',
});

// The `data` that messages.submit takes.
const data = Buffer.from(raw).toString('base64');

console.log(messageId, data.length);
TypesThe SDK’s 48 exports, as TypeScript declares them
type Address = string | { name?: string | null; email: string }
type Attachment = {
	filename: string;
	contentType?: string;
} & ({ content: Uint8Array | ArrayBuffer } | { base64: string })
type SendInput = {
	from: Address;
	to: Address | Address[];
	cc?: Address | Address[];
	bcc?: Address | Address[];
	replyTo?: Address | Address[];
	subject: string;
	text: string;
	html?: string;
	attachments?: Attachment[];
	headers?: Record<string, string>;
	mode?: 'transactional' | 'promotional';
	keepCopy?: boolean;
	deliverBy?: Date | string;
	idempotencyKey?: string;
}
type Skipped = {
	address: string;
	reason: 'private_relay' | 'disposable' | 'unsubscribed';
}
type Sent = {
	ok: true;
	id: string;
	messageId: string;
	status: 'sent' | 'queued';
	state: 'sent' | 'queued';
	sendsAt?: number;
	reason?: string;
	skipped?: Skipped[];
}
type NotSent = {
	ok: false;
	messageId: string | null;
	error: MailsetError;
}
type SendResult = Sent | NotSent
type MailsetOptions = {
	key?: string;
	token?: string;
	baseUrl?: string;
	org?: string;
	timeout?: number;
	maxRetries?: number;
	onApproval?: (approval: Approval) => void | Promise<void>;
	fetch?: (url: string, init: RequestInit) => Promise<Response>;
	now?: () => number;
}
type CallOptions = {
	org?: string;
	approval?: string;
	timeout?: number;
	signal?: AbortSignal;
}
type PasskeyPurpose = {
	kind: string;
	id: string;
	org: string | null;
}
type Approval = {
	id: string;
	url: string;
	expiresAt: number;
	purpose: PasskeyPurpose;
}
type MailsetApprovals = {
	request: (purpose: PasskeyPurpose) => Promise<Approval>;
	wait: (
		approval: Approval | string,
		options?: { timeout?: number; every?: number },
	) => Promise<string>;
}
type KeyStatus = {
	name: string;
	expiresAt: number;
	paused: string | null;
	mailboxes: {
		address: string;
		access: ('read' | 'send')[];
		sendAs: string[];
		sending: string;
	}[];
	domains: {
		name: string;
		sending: string;
		from: string[] | null;
	}[];
}
type DeliveryStatus =
	| 'sent'
	| 'delivered'
	| 'delayed'
	| 'bounced'
	| 'complained'
	| 'rejected'
	| 'expired'
	| 'skipped'
type DeliverySearchInput = {
	id?: string;
	messageId?: string;
	recipient?: string;
	sender?: string;
	status?: DeliveryStatus;
	since?: Date | number | string;
	until?: Date | number | string;
	limit?: number;
	cursor?: string;
}
type DeliveryClient = {
	name:
		| 'typescript'
		| 'python'
		| 'go'
		| 'ruby'
		| 'php'
		| 'java'
		| 'rust'
		| 'cli'
		| 'web'
		| 'ios'
		| 'other'
		| (string & {});
	version: string | null;
}
type DeliveryLine = {
	id: string;
	at: number;
	sender: string | null;
	recipient: string;
	status: DeliveryStatus;
	reason: string | null;
	message?: string;
	messageId?: string;
	client: DeliveryClient | null;
}
type DeliveryPage = {
	lines: DeliveryLine[];
	next: string | null;
}
type MailsetDelivery = {
	search: (
		input?: DeliverySearchInput,
		options?: CallOptions,
	) => Promise<DeliveryPage>;
}
type MessageFields = {
	from: Address;
	to: Address | Address[];
	cc?: Address | Address[];
	bcc?: Address | Address[];
	replyTo?: Address | Address[];
	subject: string;
	text: string;
	html?: string;
	attachments?: Attachment[];
	headers?: Record<string, string>;
}
type RawMessage = { raw: string | Uint8Array }
type CampaignMessage = (MessageFields | RawMessage) & {
	campaign: string;
	recipient: string;
	track?: { opens: boolean; clicks: boolean };
}
type CampaignSubmitInput = {
	domain: string;
	messages: readonly CampaignMessage[];
}
type MailsetCampaigns = {
	submit: (
		input: CampaignSubmitInput,
		options?: CallOptions,
	) => Promise<CampaignSubmitted>;
}
type SendingSubmitInput = (MessageFields | RawMessage) & {
	domain: string;
	ref: string;
	recipients?: string[];
}
type MailsetSending = {
	submit: (
		input: SendingSubmitInput,
		options?: CallOptions,
	) => Promise<SendingSubmitted>;
}
type MailsetKey = {
	check: () => Promise<KeyStatus>;
}
type BounceClass =
	| 'mailbox'
	| 'domain'
	| 'full'
	| 'too_large'
	| 'policy'
	| 'suppressed'
	| 'other'
type MessageEventBase = {
	id: string;
	at: number;
	message: string;
	messageId: string;
	recipient: string;
	app: string;
	duplicateOf?: string;
}
type QueuedEvent = MessageEventBase & {
	type: 'queued';
	sendsAt: number;
	reason: string;
}
type SentEvent = MessageEventBase & { type: 'sent' }
type DeliveredEvent = MessageEventBase & { type: 'delivered' }
type BouncedEvent = MessageEventBase & {
	type: 'bounced';
	bounce: { kind: 'hard' | 'soft'; class: BounceClass; reason: string };
}
type ComplainedEvent = MessageEventBase & { type: 'complained' }
type FailedEvent = MessageEventBase & { type: 'failed'; reason: string }
type ExpiredEvent = MessageEventBase & {
	type: 'expired';
	reason: string;
}
type UnsubscribedEvent = {
	type: 'unsubscribed';
	id: string;
	at: number;
	recipient: string;
	app?: string;
	message?: string;
	messageId?: string;
}
type TestEvent = { type: 'test'; id: string; at: number }
type MailEvent =
	| QueuedEvent
	| SentEvent
	| DeliveredEvent
	| BouncedEvent
	| ComplainedEvent
	| FailedEvent
	| ExpiredEvent
	| UnsubscribedEvent
	| TestEvent
type MailEventType = MailEvent['type']
type WebhookRequest = {
	body: string | Uint8Array | ArrayBuffer;
	headers: Headers | Record<string, string | string[] | undefined>;
	secret: string;
	toleranceSeconds?: number;
	now?: number;
}
type MailsetWebhooks = {
	verify: (request: WebhookRequest) => Promise<MailEvent[]>;
}
class MailsetError extends Error {
	readonly code: string;
	readonly refusal: string | null;
	readonly retryAt: number | null;
	readonly status: number | null;
	readonly timedOut: boolean;
	readonly issues: MailsetErrorIssue[];
	readonly purpose: PasskeyPurpose | null;
	readonly command: string | null;
	readonly needs: string | null;
	readonly docs: string;
	readonly help: string;
}
type MailsetErrorIssue = {
	path: (string | number)[];
	message: string;
}
type MailsetErrorDetails = {
	status?: number | null;
	timedOut?: boolean;
	cause?: unknown;
	issues?: MailsetErrorIssue[];
	purpose?: PasskeyPurpose | null;
	command?: string | null;
	needs?: string | null;
}
function messageOf(
	input: SendInput,
	now = new Date(),
	id?: string,
): { raw: string; messageId: string }
const webhooks: MailsetWebhooks
class Mailset {
	readonly key: MailsetKey;
	readonly delivery: MailsetDelivery;
	readonly webhooks: MailsetWebhooks;
	readonly campaigns: MailsetCommands['campaigns'] & MailsetCampaigns;
	readonly sending: MailsetCommands['sending'] & MailsetSending;
	readonly approvals: MailsetApprovals;
	send(input: SendInput): Promise<Sent>;
	send(inputs: readonly SendInput[]): Promise<SendResult[]>;
	request(
		command: string,
		input: Record<string, unknown> = {},
		options?: CallOptions,
	): Promise<unknown>;
}

Version and licence

This page is for version 0.7.0 of the TypeScript SDK.

You may use the SDK and change it in your own apps and services, to call Mailset. You may not publish it or pass it on, by itself or inside another library.

Something missing, or not working as this page says? Ask us.