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
Install
Add the SDK to your project.
Plain JavaScript uses the same package, with the same import.
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
MAILSET_KEY(msk1_…), an app key: sends as the mailboxes its grant names. An API token (mst_…) works here too.MAILSET_TOKEN(mst_…), an API token: a person's, for the commands no app key can run, such asdomains.add.Where Mailset is. A key names its own; a token goes to
https://mailset.app.MAILSET_APIin the environment overrides both.The org a command is about, for a person in more than one. Each call may name another.
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.
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.
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 throwsstep_up_requiredwith thepurposeto approve.Your own fetch, for tests or a proxy.
The clock every call is signed with, in ms. Only tests change it.
Returns
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.Campaign mail, from a campaigns key:
mailset.campaigns.submit.Show child attributesHide child attributes
Sends a campaign's messages, one per recipient, from a sending domain. Answers one result per message, in order:
queued, orrefusedwith why. It needs a campaigns key (mailset keys create --campaigns).
One message from a sending domain:
mailset.sending.submit.Show child attributesHide child attributes
Sends one message from a sending domain, the way a reply goes, never tracked. Answers each envelope address:
queuedorrefused.
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.Opens an approval for what a
step_up_requirederror named.Waits until it's approved, and answers the id to pass as
approval. Throwsforbiddenwhen it's refused or expires.
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.
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();
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 });
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
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).Never shown to anyone: Mailset takes it out before the message leaves.
A designed version. Without it, the text is wrapped in plain HTML.
Show child attributesHide child attributes
Attachment: A file to send with a message: its name, its type, and its bytes or their base64.Defaults to application/octet-stream.
Give this or
base64.Give this or
content.
Extra headers, such as your own
List-Unsubscribe. Addressing, subject, dates and MIME headers are Mailset's and can't be set here.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 carryList-UnsubscribeorPrecedence: bulk.promotional: a newsletter, an offer. It goes to one address into, with noccorbcc, and needs noList-Unsubscribefrom you: Mailset adds a one-click one and honors it. Write{{mailset_unsubscribe}}where the link goes, intextand as a link'shrefinhtml. 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, reasonunsubscribed), your hook hearsunsubscribed, and transactional mail still reaches them.Your own header still wins. Pass
List-Unsubscribe: <https://…>andList-Unsubscribe-Post: List-Unsubscribe=One-Clickinheaders, with the same URL in bothtextandhtml, and Mailset adds nothing: honoring those opt-outs is then yours.One of
transactionalpromotionalKeep 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 refuseskeepCopy.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, withretryAt), and mail still waiting when it comes is dropped, never sent, and shows asexpiredin the delivery log.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, callsendagain with the same key: Mailset answers the first send's receipt, the sameidandmessageId, and sends nothing new. 1 to 255 characters, no line breaks.A key belongs to its
fromaddress 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 laterfailedorexpired) 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_inputbefore anything is sent, and the message names the key and where the items are.
Returns
Promise<Sent>
Mailset took the message.
Mailset's id for this send.
The Message-ID header, without its angle brackets.
sent: it went.queued: Mailset holds it and sends it atsendsAt, because a sending limit needs time to make room or the provider stumbled. Nothing to do either way.One of
sentqueuedThe same as
status.One of
sentqueuedWhen a queued message should go out, in ms.
Why a queued message waits, in words for people.
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.One of
private_relaydisposableunsubscribed
Give sign-in codes a deadlineHonor unsubscribes and complaintsHandle skipped recipientsGuide for Node.js
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);
{
"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([...]).
Mailset took the message.
Mailset refused this one message of a batch. The rest are unaffected.
Show child attributesHide child attributes
Null when the message couldn't even be built.
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);
}
[
{
"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.
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);
List-Unsubscribe: <https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc> List-Unsubscribe-Post: List-Unsubscribe=One-Click
Three new things this month.
Leave this list: https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcThree new things this month.
Leave this list
A sample link. Mailset makes a new one for every message.
Three new things this month.
Unsubscribe: https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcThree 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.
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);
{
"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.
The app's name, as approved.
When the key stops working, in ms. Every call moves it 90 days out.
Why Mailset stopped this app's mail (too many bounces or complaints), or null.
A mailbox key's mailbox. Empty for a domain key.
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.
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);
}
{
"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
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.Only the lines of one send: the
idits receipt answered.Only the lines of the message with this Message-ID, the
messageIdits receipt answered.A recipient's whole address, or part of one, such as
@example.org.One of the addresses this key sends as, or part of one.
Only lines with this status.
One of
sentdelivereddelayedbouncedcomplainedrejectedexpiredskippedFrom this moment on: a
Date, a time in ms, or a day as'2026-11-30', which counts from its start in UTC.Up to this moment, written like
since. A day counts to its end in UTC.How many lines a page holds, 1 to 200. 50 unless told.
The
nextof the page before, for the page after it.
Show child attributesHide child attributes
CallOptions: What every command method takes beside its input.The org this is about, by its id: for a person in more than one.
An approval's id, once someone approved it with their passkey: see
approvals.How long one try may take, in ms, for this call alone.
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.The line's id.
When it happened, in ms.
The mailbox it left from, whichever of its addresses was in From. For a domain key's mail, the address it went as.
The address it went to.
One of
sentdelivereddelayedbouncedcomplainedrejectedexpiredskippedWhy, in words for people, when the status needs saying why.
The send this line is about: the
idits receipt answered.Its Message-ID header, without the angle brackets:
messageIdfromsend.Which client sent it. Null when its request named none.
Show child attributesHide child attributes
DeliveryClient: Which client sent a message, from theMailset-Clientheader its request carried: one of Mailset's SDKs by its language,cli,web,ios, orother. A name this version doesn't know yet still shows, as Mailset names it.Its version, as it said. Null for
other.
Pass it back as
cursorfor the next page. Null on the last one.
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);
{
"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
The body exactly as it arrived, before any JSON parsing: the signature covers these bytes.
The request's headers: a
Headers, or Node'sreq.headers.The hook's signing secret, from
mailset hooks set.How old a signature may be, in seconds. 300 unless told.
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.
A limit holds it, so it goes out later.
Show child attributesHide child attributes
Stable for this message, recipient and happening: dedupe on it.
When it happened, in ms.
Mailset's id for the message: the
idthatsendanswered.Its Message-ID header, without the angle brackets:
messageIdfromsend.One recipient: a message to three people has three of each event.
The app key that sent it, by the name it was approved with.
Present when the same content went to this recipient from the same address less than 10 minutes before, under another Message-ID: the
messageof that earlier send. Both were sent. It most often means a retry without anidempotencyKey: give the send one and the second never goes.When it should go out, in ms.
The provider took it.
Show child attributesHide child attributes
Stable for this message, recipient and happening: dedupe on it.
When it happened, in ms.
Mailset's id for the message: the
idthatsendanswered.Its Message-ID header, without the angle brackets:
messageIdfromsend.One recipient: a message to three people has three of each event.
The app key that sent it, by the name it was approved with.
Present when the same content went to this recipient from the same address less than 10 minutes before, under another Message-ID: the
messageof that earlier send. Both were sent. It most often means a retry without anidempotencyKey: give the send one and the second never goes.
The recipient's server took it.
Show child attributesHide child attributes
Stable for this message, recipient and happening: dedupe on it.
When it happened, in ms.
Mailset's id for the message: the
idthatsendanswered.Its Message-ID header, without the angle brackets:
messageIdfromsend.One recipient: a message to three people has three of each event.
The app key that sent it, by the name it was approved with.
Present when the same content went to this recipient from the same address less than 10 minutes before, under another Message-ID: the
messageof that earlier send. Both were sent. It most often means a retry without anidempotencyKey: give the send one and the second never goes.
It came back.
hardwon't change;softmay go on a later try.Show child attributesHide child attributes
Stable for this message, recipient and happening: dedupe on it.
When it happened, in ms.
Mailset's id for the message: the
idthatsendanswered.Its Message-ID header, without the angle brackets:
messageIdfromsend.One recipient: a message to three people has three of each event.
The app key that sent it, by the name it was approved with.
Present when the same content went to this recipient from the same address less than 10 minutes before, under another Message-ID: the
messageof that earlier send. Both were sent. It most often means a retry without anidempotencyKey: give the send one and the second never goes.Show child attributesHide child attributes
One of
hardsoftOne of
mailboxdomainfulltoo_largepolicysuppressedother
The recipient marked it as spam. Stop writing to them.
Show child attributesHide child attributes
Stable for this message, recipient and happening: dedupe on it.
When it happened, in ms.
Mailset's id for the message: the
idthatsendanswered.Its Message-ID header, without the angle brackets:
messageIdfromsend.One recipient: a message to three people has three of each event.
The app key that sent it, by the name it was approved with.
Present when the same content went to this recipient from the same address less than 10 minutes before, under another Message-ID: the
messageof that earlier send. Both were sent. It most often means a retry without anidempotencyKey: give the send one and the second never goes.
Mailset couldn't send it: the provider refused it, its app was paused, or five tries failed.
Show child attributesHide child attributes
Stable for this message, recipient and happening: dedupe on it.
When it happened, in ms.
Mailset's id for the message: the
idthatsendanswered.Its Message-ID header, without the angle brackets:
messageIdfromsend.One recipient: a message to three people has three of each event.
The app key that sent it, by the name it was approved with.
Present when the same content went to this recipient from the same address less than 10 minutes before, under another Message-ID: the
messageof that earlier send. Both were sent. It most often means a retry without anidempotencyKey: give the send one and the second never goes.
Its
deliverBycame while it waited, so it never went.Show child attributesHide child attributes
Stable for this message, recipient and happening: dedupe on it.
When it happened, in ms.
Mailset's id for the message: the
idthatsendanswered.Its Message-ID header, without the angle brackets:
messageIdfromsend.One recipient: a message to three people has three of each event.
The app key that sent it, by the name it was approved with.
Present when the same content went to this recipient from the same address less than 10 minutes before, under another Message-ID: the
messageof that earlier send. Both were sent. It most often means a retry without anidempotencyKey: give the send one and the second never goes.
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
Stable for this opt-out. Someone let back in who leaves again has a new one.
When they unsubscribed, in ms.
The address that unsubscribed, in lowercase.
The app key whose mail the link was in, by the name it was approved with.
Mailset's id for the message the link was in: the
idthatsendanswered.That message's Message-ID header, without the angle brackets.
From
mailset hooks testor the settings page: about no message.
Attributes
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
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;
}
}
// 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;
}
}
[
{
"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
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: seeSent.skipped.On
limit_reachedfor mail with adeliverBy: the soonest it could go, in ms. Send it again then, or with a laterdeliverBy.The HTTP status Mailset answered with, or null when it didn't answer.
True when the last try ran out of its
timeoutbefore Mailset answered.codeis thenunavailable, as for a network failure.On
invalid_input: each field that was wrong, and what's wrong with it.On
step_up_required: what a passkey has to approve. Seeapprovals.The command that was refused, by its id, when it was one.
When this credential can't run the command: the one that can,
MAILSET_TOKENorMAILSET_KEY, with the grant it needs.Where the docs say what this
codemeans and what to do.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.
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);
}
{
"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
Default
new Date().
Returns
object
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.