# TypeScript and JavaScript

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

- **Every public command**: 238 commands, each a typed method
- **No dependencies**: Nothing else to install beside it
- **30 KB**: The whole SDK, minified, as one ES module
- **Typed throughout**: Types for every command and answer
- **Retries built in**: Two more tries, and a send never doubles
- **Timeouts per try**: 30 seconds a try, then tried again

## Requirements

- Node.js 20 or later (tested: a real send runs on it)
- Bun 1.4 or later (tested: a real send runs on it)
- Deno 2.9 or later (tested: a real send runs on it)
- Cloudflare Workers, from 2024-01-01 (tested: a real send runs on it)

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

## Install

npm:

```bash
npm install mailset
```

pnpm:

```bash
pnpm add mailset
```

bun:

```bash
bun add mailset
```

yarn:

```bash
yarn add mailset
```

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

```typescript
import { Mailset } from 'mailset';
```

## Create a client

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

```typescript
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](https://mailset.app/docs/sdk/typescript#types-MailsetOptions)

- `key` (string, optional): `MAILSET_KEY` (`msk1_…`), an app key: sends as the mailboxes its grant names. An API token (`mst_…`) works here too.
- `token` (string, optional): `MAILSET_TOKEN` (`mst_…`), an API token: a person's, for the commands no app key can run, such as `domains.add`.
- `baseUrl` (string, optional): Where Mailset is. A key names its own; a token goes to `https://mailset.app`. `MAILSET_API` in the environment overrides both.
- `org` (string, optional): The org a command is about, for a person in more than one. Each call may name another.
- `timeout` (number, optional): 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.
- `maxRetries` (number, optional): 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](https://mailset.app/docs/sdk/typescript#types-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` (() =\> number, optional): The clock every call is signed with, in ms. Only tests change it.

### Returns

[Mailset](https://mailset.app/docs/sdk/typescript#types-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.

- `key` ([MailsetKey](https://mailset.app/docs/sdk/typescript#key)): This client's `MAILSET_KEY`.
- `delivery` ([MailsetDelivery](https://mailset.app/docs/sdk/typescript#delivery)): What became of the mail this key sent.
- `webhooks` ([MailsetWebhooks](https://mailset.app/docs/sdk/typescript#webhooks)): Events from your org's hook: the same object as the standalone `webhooks`.
- `campaigns` (object): Campaign mail, from a campaigns key: `mailset.campaigns.submit`.
  - `submit` ((input: [CampaignSubmitInput](https://mailset.app/docs/sdk/typescript#types-CampaignSubmitInput), options?: [CallOptions](https://mailset.app/docs/sdk/typescript#types-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`).
- `sending` (object): One message from a sending domain: `mailset.sending.submit`.
  - `submit` ((input: [SendingSubmitInput](https://mailset.app/docs/sdk/typescript#types-SendingSubmitInput), options?: [CallOptions](https://mailset.app/docs/sdk/typescript#types-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` ([MailsetApprovals](https://mailset.app/docs/sdk/typescript#types-MailsetApprovals)): Approvals for commands that need a passkey. `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](https://mailset.app/docs/sdk/typescript#types-PasskeyPurpose)) =\> Promise\<[Approval](https://mailset.app/docs/sdk/typescript#types-Approval)\>): Opens an approval for what a `step_up_required` error named.
  - `wait` ((approval: [Approval](https://mailset.app/docs/sdk/typescript#types-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.
- `send` (function): See [Send](https://mailset.app/docs/sdk/typescript#send) and [Send many](https://mailset.app/docs/sdk/typescript#send-many).
- `request` ((command: string, input?: Record\<string, unknown\>, options?: [CallOptions](https://mailset.app/docs/sdk/typescript#types-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`.

### Example

```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

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

```typescript
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

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.

```typescript
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());
```

More: [Authentication](https://mailset.app/docs/authentication)

## Send

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

```typescript
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](https://mailset.app/docs/sdk/typescript#types-SendInput)

- `from` ([Address](https://mailset.app/docs/sdk/typescript#types-Address), required): 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`). `Address`: `ana@example.com`, `Ana <ana@example.com>`, or the two parts.
  - `name` (string | null, optional)
  - `email` (string, required)
- `to` ([Address](https://mailset.app/docs/sdk/typescript#types-Address) | [Address](https://mailset.app/docs/sdk/typescript#types-Address)[], required): `Address`: `ana@example.com`, `Ana <ana@example.com>`, or the two parts.
  - `name` (string | null, optional)
  - `email` (string, required)
- `cc` ([Address](https://mailset.app/docs/sdk/typescript#types-Address) | [Address](https://mailset.app/docs/sdk/typescript#types-Address)[], optional): `Address`: `ana@example.com`, `Ana <ana@example.com>`, or the two parts.
  - `name` (string | null, optional)
  - `email` (string, required)
- `bcc` ([Address](https://mailset.app/docs/sdk/typescript#types-Address) | [Address](https://mailset.app/docs/sdk/typescript#types-Address)[], optional): Never shown to anyone: Mailset takes it out before the message leaves. `Address`: `ana@example.com`, `Ana <ana@example.com>`, or the two parts.
  - `name` (string | null, optional)
  - `email` (string, required)
- `replyTo` ([Address](https://mailset.app/docs/sdk/typescript#types-Address) | [Address](https://mailset.app/docs/sdk/typescript#types-Address)[], optional): `Address`: `ana@example.com`, `Ana <ana@example.com>`, or the two parts.
  - `name` (string | null, optional)
  - `email` (string, required)
- `subject` (string, required)
- `text` (string, required)
- `html` (string, optional): A designed version. Without it, the text is wrapped in plain HTML.
- `attachments` ([Attachment](https://mailset.app/docs/sdk/typescript#types-Attachment)[], optional): `Attachment`: A file to send with a message: its name, its type, and its bytes or their base64.
  - `filename` (string, required)
  - `contentType` (string, optional): Defaults to application/octet-stream.
  - `content` (Uint8Array | ArrayBuffer, required): Give this or `base64`.
  - `base64` (string, required): Give this or `content`.
- `headers` (Record\<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.
- `mode` (enum, optional): `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 of `transactional`, `promotional`.
- `keepCopy` (boolean, optional): 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`.
- `deliverBy` (Date | string, optional): 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.
- `idempotencyKey` (string, optional): 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](https://mailset.app/docs/sdk/typescript#types-Sent)\>

Mailset took the message.

- `ok` (true)
- `id` (string): Mailset's id for this send.
- `messageId` (string): The Message-ID header, without its angle brackets.
- `status` (enum): `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 of `sent`, `queued`.
- `state` (enum): The same as `status`. One of `sent`, `queued`.
- `sendsAt` (number, optional): When a queued message should go out, in ms.
- `reason` (string, optional): Why a queued message waits, in words for people.
- `skipped` ([Skipped](https://mailset.app/docs/sdk/typescript#types-Skipped)[], 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. `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.
  - `address` (string)
  - `reason` (enum): One of `private_relay`, `disposable`, `unsubscribed`.

### Example

```typescript
import { Mailset } from 'mailset';

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

const sent = await mailset.send({
	from: 'Acme <hello@example.com>',
	to: 'ana@example.org',
	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:

```json
{
  "ok": true,
  "id": "out_3f9a1c0e7b2d",
  "messageId": "3f9a1c0e7b2d4a58@example.com",
  "status": "sent",
  "state": "sent"
}
```

More: [Give sign-in codes a deadline](https://mailset.app/docs/recipes/deadlines), [Honor unsubscribes and complaints](https://mailset.app/docs/recipes/unsubscribes), [Handle skipped recipients](https://mailset.app/docs/recipes/skipped), [Guide for Node.js](https://mailset.app/send-email/nodejs)

## 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.

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

### Parameters

- `inputs` ([SendInput](https://mailset.app/docs/sdk/typescript#send-parameters)[], required)

### Returns

Promise\<[SendResult](https://mailset.app/docs/sdk/typescript#types-SendResult)[]\>

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

- `Sent` ([Sent](https://mailset.app/docs/sdk/typescript#send-returns)): Mailset took the message.
- `NotSent` (object): Mailset refused this one message of a batch. The rest are unaffected.
  - `ok` (false)
  - `messageId` (string | null): Null when the message couldn't even be built.
  - `error` ([MailsetError](https://mailset.app/docs/sdk/typescript#errors))

### Example

```typescript
import { Mailset } from 'mailset';

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

const results = await mailset.send([
	{
		from: 'Acme <hello@example.com>',
		to: 'ana@example.org',
		subject: 'Your invoice',
		text: 'Invoice 8842 is ready.',
	},
	{
		from: 'Acme <hello@example.com>',
		to: 'ben@example.org',
		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:

```json
[
  {
    "ok": true,
    "id": "out_3f9a1c0e7b2d",
    "messageId": "3f9a1c0e7b2d4a58@example.com",
    "status": "sent",
    "state": "sent"
  },
  {
    "ok": false,
    "messageId": "8d2k4m1p9q7x5b1f@example.com",
    "error": {
      "code": "forbidden",
      "message": "This app can’t send as that address.",
      "refusal": null,
      "retryAt": null
    }
  }
]
```

More: [Send many messages at once](https://mailset.app/docs/recipes/batches)

## 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.

### Example

```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 <news@news.example.com>',
	to: 'ana@example.org',
	subject: 'What shipped in March',
	text,
	html,
	mode: 'promotional',
});

console.log(sent.id, sent.skipped);
```

### What Ana receives

Headers Mailset adds:

```text
List-Unsubscribe: <https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc>
List-Unsubscribe-Post: List-Unsubscribe=One-Click
```

The text part:

```text
Three new things this month.

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

The HTML part:

```html
<p>Three new things this month.</p>
<a href="https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc">Leave this list</a>
```

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

### What Ana receives without the placeholder

The text part:

```text
Three new things this month.

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

The HTML part:

```html
<p>Three new things this month.</p><p><a href="https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc">Unsubscribe</a></p>
```

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

More: [Honor unsubscribes and complaints](https://mailset.app/docs/recipes/unsubscribes), [Handle skipped recipients](https://mailset.app/docs/recipes/skipped)

## 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.

### Example

```typescript
import { Mailset, type SendInput } from 'mailset';

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

const receipt: SendInput = {
	from: 'Acme <hello@example.com>',
	to: 'ana@example.org',
	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:

```json
{
  "ok": true,
  "id": "out_3f9a1c0e7b2d",
  "messageId": "3f9a1c0e7b2d4a58@example.com",
  "status": "sent",
  "state": "sent"
}
```

More: [Retry without sending twice](https://mailset.app/docs/recipes/retries)

## 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.

```typescript
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](https://mailset.app/docs/sdk/typescript#types-KeyStatus)\>

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

- `name` (string): The app's name, as approved.
- `expiresAt` (number): When the key stops working, in ms. Every call moves it 90 days out.
- `paused` (string | null): Why Mailset stopped this app's mail (too many bounces or complaints), or null.
- `mailboxes` (array of objects): A mailbox key's mailbox. Empty for a domain key.
  - `address` (string)
  - `access` (array of enums): One of `read`, `send`.
  - `sendAs` (string[]): The addresses it may send as: the mailbox and its aliases.
  - `sending` (string): `ready`: its domain can send.
- `domains` (array 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.
  - `name` (string): `example.com`. Its subdomains aren't covered.
  - `sending` (string): `ready`: it can send.
  - `from` (string[] | 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.

### Example

```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:

```json
{
  "name": "Acme API",
  "expiresAt": 1803824940000,
  "paused": null,
  "mailboxes": [
    {
      "address": "hello@example.com",
      "access": [
        "send"
      ],
      "sendAs": [
        "hello@example.com"
      ],
      "sending": "ready"
    }
  ],
  "domains": []
}
```

More: [Keep a key alive](https://mailset.app/docs/recipes/keys)

## Delivery search

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

```typescript
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

- `input` ([DeliverySearchInput](https://mailset.app/docs/sdk/typescript#types-DeliverySearchInput), optional): `DeliverySearchInput`: Which lines of the delivery log to find. Every field narrows the search; with none, you get the newest.
  - `id` (string, optional): Only the lines of one send: the `id` its receipt answered.
  - `messageId` (string, optional): Only the lines of the message with this Message-ID, the `messageId` its receipt answered.
  - `recipient` (string, optional): A recipient's whole address, or part of one, such as `@example.org`.
  - `sender` (string, optional): One of the addresses this key sends as, or part of one.
  - `status` ([DeliveryStatus](https://mailset.app/docs/sdk/typescript#types-DeliveryStatus), optional): Only lines with this status. One of `sent`, `delivered`, `delayed`, `bounced`, `complained`, `rejected`, `expired`, `skipped`. `DeliveryStatus`: What became of a message for one recipient. `sent`: Mailset handed it on. `delivered`: the recipient's server took it. `delayed`: that server asked to try later, and it will be. `bounced`: it came back. `complained`: the recipient marked it as spam. `rejected`: it was refused before it left. `expired`: its `deliverBy` came while it waited. `skipped`: Mailset left the address out on purpose (see `Sent.skipped`).
  - `since` (Date | number | string, optional): From this moment on: a `Date`, a time in ms, or a day as `'2026-11-30'`, which counts from its start in UTC.
  - `until` (Date | number | string, optional): Up to this moment, written like `since`. A day counts to its end in UTC.
  - `limit` (number, optional): How many lines a page holds, 1 to 200. 50 unless told.
  - `cursor` (string, optional): The `next` of the page before, for the page after it.
- `options` ([CallOptions](https://mailset.app/docs/sdk/typescript#types-CallOptions), optional): `CallOptions`: What every command method takes beside its input.
  - `org` (string, optional): The org this is about, by its id: for a person in more than one.
  - `approval` (string, optional): An approval's id, once someone approved it with their passkey: see `approvals`.
  - `timeout` (number, optional): How long one try may take, in ms, for this call alone.
  - `signal` (AbortSignal, optional): Stops the call.

### Returns

Promise\<[DeliveryPage](https://mailset.app/docs/sdk/typescript#types-DeliveryPage)\>

One page of the delivery log, newest first.

- `lines` ([DeliveryLine](https://mailset.app/docs/sdk/typescript#types-DeliveryLine)[]): `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.
  - `id` (string): The line's id.
  - `at` (number): When it happened, in ms.
  - `sender` (string | null): The mailbox it left from, whichever of its addresses was in From. For a domain key's mail, the address it went as.
  - `recipient` (string): The address it went to.
  - `status` ([DeliveryStatus](https://mailset.app/docs/sdk/typescript#types-DeliveryStatus)): One of `sent`, `delivered`, `delayed`, `bounced`, `complained`, `rejected`, `expired`, `skipped`. `DeliveryStatus`: What became of a message for one recipient. `sent`: Mailset handed it on. `delivered`: the recipient's server took it. `delayed`: that server asked to try later, and it will be. `bounced`: it came back. `complained`: the recipient marked it as spam. `rejected`: it was refused before it left. `expired`: its `deliverBy` came while it waited. `skipped`: Mailset left the address out on purpose (see `Sent.skipped`).
  - `reason` (string | null): Why, in words for people, when the status needs saying why.
  - `message` (string, optional): The send this line is about: the `id` its receipt answered.
  - `messageId` (string, optional): Its Message-ID header, without the angle brackets: `messageId` from `send`.
  - `client` ([DeliveryClient](https://mailset.app/docs/sdk/typescript#types-DeliveryClient) | null): Which client sent it. Null when its request named none. `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)
    - `version` (string | null): Its version, as it said. Null for `other`.
- `next` (string | null): Pass it back as `cursor` for the next page. Null on the last one.

### Example

```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: 'ana@example.org',
	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:

```json
{
  "lines": [
    {
      "id": "dlv_8d2k4m1p9q7x",
      "at": 1796048940000,
      "sender": "hello@example.com",
      "recipient": "ana@example.org",
      "status": "bounced",
      "reason": "smtp; 550 5.1.1 The email account that you tried to reach does not exist.",
      "message": "out_3f9a1c0e7b2d",
      "messageId": "3f9a1c0e7b2d4a58@example.com",
      "client": {
        "name": "typescript",
        "version": "0.7.0"
      }
    }
  ],
  "next": null
}
```

More: [Handle bounces](https://mailset.app/docs/recipes/bounces)

## 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.

```typescript
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](https://mailset.app/docs/sdk/typescript#types-WebhookRequest)

- `body` (string | Uint8Array | ArrayBuffer, required): The body exactly as it arrived, before any JSON parsing: the signature covers these bytes.
- `headers` (Headers | Record\<string, string | string[] | undefined\>, required): The request's headers: a `Headers`, or Node's `req.headers`.
- `secret` (string, required): The hook's signing secret, from `mailset hooks set`.
- `toleranceSeconds` (number, optional): How old a signature may be, in seconds. 300 unless told.
- `now` (number, optional): The clock, in ms. Only tests change it.

### Returns

Promise\<[MailEvent](https://mailset.app/docs/sdk/typescript#types-MailEvent)[]\>

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

- `QueuedEvent` (object): A limit holds it, so it goes out later.
  - `id` (string): Stable for this message, recipient and happening: dedupe on it.
  - `at` (number): When it happened, in ms.
  - `message` (string): Mailset's id for the message: the `id` that `send` answered.
  - `messageId` (string): Its Message-ID header, without the angle brackets: `messageId` from `send`.
  - `recipient` (string): One recipient: a message to three people has three of each event.
  - `app` (string): The app key that sent it, by the name it was approved with.
  - `duplicateOf` (string, optional): 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')
  - `sendsAt` (number): When it should go out, in ms.
  - `reason` (string)
- `SentEvent` (object): The provider took it.
  - `id` (string): Stable for this message, recipient and happening: dedupe on it.
  - `at` (number): When it happened, in ms.
  - `message` (string): Mailset's id for the message: the `id` that `send` answered.
  - `messageId` (string): Its Message-ID header, without the angle brackets: `messageId` from `send`.
  - `recipient` (string): One recipient: a message to three people has three of each event.
  - `app` (string): The app key that sent it, by the name it was approved with.
  - `duplicateOf` (string, optional): 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')
- `DeliveredEvent` (object): The recipient's server took it.
  - `id` (string): Stable for this message, recipient and happening: dedupe on it.
  - `at` (number): When it happened, in ms.
  - `message` (string): Mailset's id for the message: the `id` that `send` answered.
  - `messageId` (string): Its Message-ID header, without the angle brackets: `messageId` from `send`.
  - `recipient` (string): One recipient: a message to three people has three of each event.
  - `app` (string): The app key that sent it, by the name it was approved with.
  - `duplicateOf` (string, optional): 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')
- `BouncedEvent` (object): It came back. `hard` won't change; `soft` may go on a later try.
  - `id` (string): Stable for this message, recipient and happening: dedupe on it.
  - `at` (number): When it happened, in ms.
  - `message` (string): Mailset's id for the message: the `id` that `send` answered.
  - `messageId` (string): Its Message-ID header, without the angle brackets: `messageId` from `send`.
  - `recipient` (string): One recipient: a message to three people has three of each event.
  - `app` (string): The app key that sent it, by the name it was approved with.
  - `duplicateOf` (string, optional): 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')
  - `bounce` (object)
    - `kind` (enum): One of `hard`, `soft`.
    - `class` ([BounceClass](https://mailset.app/docs/sdk/typescript#types-BounceClass)): One of `mailbox`, `domain`, `full`, `too_large`, `policy`, `suppressed`, `other`. `BounceClass`: How a bounce reads: `mailbox` and `domain` mean the address can't get mail.
    - `reason` (string)
- `ComplainedEvent` (object): The recipient marked it as spam. Stop writing to them.
  - `id` (string): Stable for this message, recipient and happening: dedupe on it.
  - `at` (number): When it happened, in ms.
  - `message` (string): Mailset's id for the message: the `id` that `send` answered.
  - `messageId` (string): Its Message-ID header, without the angle brackets: `messageId` from `send`.
  - `recipient` (string): One recipient: a message to three people has three of each event.
  - `app` (string): The app key that sent it, by the name it was approved with.
  - `duplicateOf` (string, optional): 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')
- `FailedEvent` (object): Mailset couldn't send it: the provider refused it, its app was paused, or five tries failed.
  - `id` (string): Stable for this message, recipient and happening: dedupe on it.
  - `at` (number): When it happened, in ms.
  - `message` (string): Mailset's id for the message: the `id` that `send` answered.
  - `messageId` (string): Its Message-ID header, without the angle brackets: `messageId` from `send`.
  - `recipient` (string): One recipient: a message to three people has three of each event.
  - `app` (string): The app key that sent it, by the name it was approved with.
  - `duplicateOf` (string, optional): 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')
  - `reason` (string)
- `ExpiredEvent` (object): Its `deliverBy` came while it waited, so it never went.
  - `id` (string): Stable for this message, recipient and happening: dedupe on it.
  - `at` (number): When it happened, in ms.
  - `message` (string): Mailset's id for the message: the `id` that `send` answered.
  - `messageId` (string): Its Message-ID header, without the angle brackets: `messageId` from `send`.
  - `recipient` (string): One recipient: a message to three people has three of each event.
  - `app` (string): The app key that sent it, by the name it was approved with.
  - `duplicateOf` (string, optional): 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')
  - `reason` (string)
- `UnsubscribedEvent` (object): 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.
  - `type` ('unsubscribed')
  - `id` (string): Stable for this opt-out. Someone let back in who leaves again has a new one.
  - `at` (number): When they unsubscribed, in ms.
  - `recipient` (string): The address that unsubscribed, in lowercase.
  - `app` (string, optional): The app key whose mail the link was in, by the name it was approved with.
  - `message` (string, optional): Mailset's id for the message the link was in: the `id` that `send` answered.
  - `messageId` (string, optional): That message's Message-ID header, without the angle brackets.
- `TestEvent` (object): From `mailset hooks test` or the settings page: about no message.
  - `type` ('test')
  - `id` (string)
  - `at` (number)

### Attributes

- `MailEventType` ([MailEvent](https://mailset.app/docs/sdk/typescript#webhooks-returns)['type']): Every event's `type`, as a union of the words.

### Example

```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;
	}
}
```

Returns:

```json
[
  {
    "type": "bounced",
    "id": "evt_5b1f0c9a7e3d",
    "at": 1796048940000,
    "message": "out_3f9a1c0e7b2d",
    "messageId": "3f9a1c0e7b2d4a58@example.com",
    "recipient": "ana@example.org",
    "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."
    }
  }
]
```

### 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.

```typescript
// 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;
	}
}
```

More: [Webhooks](https://mailset.app/docs/webhooks), [Handle bounces](https://mailset.app/docs/recipes/bounces), [Guide for Next.js](https://mailset.app/send-email/nextjs), [Guide for Express](https://mailset.app/send-email/express), [Guide for NestJS](https://mailset.app/send-email/nestjs), [Guide for Cloudflare Workers](https://mailset.app/send-email/cloudflare-workers)

## 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

- `code` (string)
- `refusal` (string | 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`.
- `retryAt` (number | 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`.
- `status` (number | null): The HTTP status Mailset answered with, or null when it didn't answer.
- `timedOut` (boolean): True when the last try ran out of its `timeout` before Mailset answered. `code` is then `unavailable`, as for a network failure.
- `issues` ([MailsetErrorIssue](https://mailset.app/docs/sdk/typescript#types-MailsetErrorIssue)[]): On `invalid_input`: each field that was wrong, and what's wrong with it. `MailsetErrorIssue`: One wrong field of an `invalid_input`.
  - `path` ((string | number)[]): Which input field: its name, then any keys inside it.
  - `message` (string)
- `purpose` ([PasskeyPurpose](https://mailset.app/docs/sdk/typescript#types-PasskeyPurpose) | null): On `step_up_required`: what a passkey has to approve. See `approvals`. `PasskeyPurpose`: What a passkey has to approve, as a `step_up_required` error names it.
  - `kind` (string): What it's about: a `domain`, a `mailbox`, a `member` and so on.
  - `id` (string): The action itself.
  - `org` (string | null): The org it's in, or null for a person's own account.
- `command` (string | null): The command that was refused, by its id, when it was one.
- `needs` (string | null): When this credential can't run the command: the one that can, `MAILSET_TOKEN` or `MAILSET_KEY`, with the grant it needs.
- `docs` (string): Where the docs say what this `code` means and what to do.
- `help` (string): The docs' link and where to ask, in one line: what a log should keep beside `message`.

### Example

```typescript
import { Mailset, MailsetError } from 'mailset';

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

try {
	await mailset.send({
		from: 'Acme <hello@example.com>',
		to: 'ana@example.org',
		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:

```json
{
  "code": "limit_reached",
  "message": "The day’s sending limit is reached.",
  "refusal": null,
  "retryAt": 1796052540000
}
```

### 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.

More: [Errors and limits](https://mailset.app/docs/errors)

## 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.

```typescript
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

- `input` ([SendInput](https://mailset.app/docs/sdk/typescript#send-parameters), required)
- `now` (Date, optional): Default `new Date()`.
- `id` (string, optional)

### Returns

object

- `raw` (string)
- `messageId` (string)

### Example

```typescript
import { messageOf } from 'mailset';

const { raw, messageId } = messageOf({
	from: 'Acme <hello@example.com>',
	to: 'ana@example.org',
	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);
```

More: [messages.submit](https://mailset.app/docs/api/messages#messages.submit)

## Types

The SDK’s exports, as TypeScript declares them.

```typescript
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 at https://mailset.app/support, or run `mailset feedback "<message>"` in a terminal.

---

© 2026 Intenseloop, Inc. Mailset’s site, docs and guides are copyrighted. You may read them and use their code to build with Mailset. Don’t republish them or use them to build a copy of Mailset. Terms: https://mailset.app/terms#content