postbound 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,1023 @@
1
- # Temporary Holding Version
1
+ <div align="left">
2
+ <img src="https://cdn.paddlewheel.org/paddlewheel/paddlewheelfullbrand.svg" height="25px" alt="Postbound" />
3
+ </div>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ # postbound-node
6
+
7
+ > [!NOTE]
8
+ > This is a **public repository** maintained by **Paddlewheel Inc.** The code is open source under the [MIT License](LICENSE).
9
+
10
+ Node.js and TypeScript SDK for [Postbound](https://postbound.app). Use it to send, schedule, and receive email, and to manage domains, API keys, audiences, contacts, and webhooks through the Postbound API. It mirrors [resend-node](https://github.com/resend/resend-node), so moving from Resend is mostly a rename.
11
+
12
+ This package sends requests with your API key to the Postbound API and handles your email content. Never put a real API key in code, tests, logs, issues, or screenshots.
13
+
14
+ ## Contributing
15
+
16
+ Issues and pull requests are welcome. For a bug, include the SDK version, your Node.js version, and the `request_id` from the error response if you have one. For a larger change, open an issue first so we can agree on the approach before you write the code.
17
+
18
+ Pull requests are reviewed by the Postbound team, and a change is only released after a maintainer approves and merges it. CI and CodeQL must pass before a pull request can be merged. See [CONTRIBUTING.md](CONTRIBUTING.md) for the code rules and the pull request process.
19
+
20
+ Report security problems privately through [GitHub private vulnerability reporting](https://github.com/Paddlewheel-Inc/postbound-node/security/advisories/new) instead of opening a public issue. See [SECURITY.md](SECURITY.md).
21
+
22
+ ## License and trademarks
23
+
24
+ The source code is released under the [MIT License](LICENSE), Copyright (c) 2026 Paddlewheel Inc.
25
+
26
+ The **Postbound** name, logo, and associated branding are the property of Paddlewheel Inc. and are protected by applicable trademark, copyright, and intellectual property laws. The MIT License covers the code, not the branding. Unauthorised use, reproduction, modification, or representation of Postbound branding is not permitted without prior written consent from Paddlewheel Inc.
27
+
28
+ ## Tech stack
29
+
30
+ - **Language:** [TypeScript](https://www.typescriptlang.org) `^7`
31
+ - **Runtime:** [Node.js](https://nodejs.org) 20+, using the built-in `fetch`
32
+ - **Webhook signatures:** [Standard Webhooks](https://www.standardwebhooks.com) `^1.1`, the only runtime dependency
33
+ - **Email templates:** [React Email](https://react.email) via `@react-email/render`, an optional peer dependency
34
+ - **Build:** [tsdown](https://tsdown.dev) `^0.23`, which emits ESM, CommonJS, and type declarations
35
+ - **Linting and formatting:** [Biome](https://biomejs.dev) `^2`
36
+ - **Package manager:** [pnpm](https://pnpm.io)
37
+
38
+ ## Getting started
39
+
40
+ You need Node.js 22.13+ and pnpm 11 to work on the SDK. Using the SDK only needs Node.js 20+.
41
+
42
+ ```bash
43
+ git clone https://github.com/Paddlewheel-Inc/postbound-node.git
44
+ cd postbound-node
45
+ pnpm install
46
+ pnpm build
47
+ ```
48
+
49
+ To try your changes against the API, create an API key in the Postbound portal and run a script against `src`:
50
+
51
+ ```ts
52
+ import { Postbound } from './src';
53
+
54
+ const postbound = new Postbound(process.env.POSTBOUND_API_KEY);
55
+
56
+ console.log(await postbound.domains.list());
57
+ ```
58
+
59
+ Use a key from a test account where you can, and a `sending_access` key if you only need to send.
60
+
61
+ ## Environment variables
62
+
63
+ The SDK reads these variables when the matching constructor option is not set. Do not commit `.env` files, API keys, or webhook signing secrets.
64
+
65
+ | Variable | Purpose | Default |
66
+ | ---------------------- | --------------------------------------------------- | --------------------------- |
67
+ | `POSTBOUND_API_KEY` | API key used when none is passed to the constructor | none, required |
68
+ | `POSTBOUND_BASE_URL` | API base URL | `https://api.postbound.app` |
69
+ | `POSTBOUND_USER_AGENT` | `User-Agent` header | `postbound-node:<version>` |
70
+ | `POSTBOUND_DEBUG` | Set to `true` to log every API error to stderr | off |
71
+
72
+ Explicit constructor options win over environment variables, and empty variables are ignored.
73
+
74
+ If a key or secret is committed by accident, treat it as compromised, and revoke it in the Postbound portal immediately. Deleting the file from git is not enough, because it stays in the history.
75
+
76
+ ## Scripts
77
+
78
+ Scripts are defined in `package.json` and should be invoked through pnpm.
79
+
80
+ | Command | What it does |
81
+ | -------------------- | ----------------------------------------------------------------- |
82
+ | `pnpm install` | Install dependencies |
83
+ | `pnpm build` | Bundle ESM, CommonJS, and type declarations into `dist` |
84
+ | `pnpm lint` | Run Biome checks |
85
+ | `pnpm lint:fix` | Apply Biome fixes |
86
+ | `pnpm typecheck` | Run TypeScript without emitting |
87
+ | `pnpm check:pinned` | Require exact dependency versions |
88
+ | `pnpm check:source` | Reject comments, suppressions, TODOs, and hardcoded keys in `src` |
89
+ | `pnpm check:package` | Verify the built package exports and type resolution |
90
+ | `pnpm check` | Run every check above, the same as CI |
91
+ ## Usage
92
+
93
+ ### Installation
94
+
95
+ ```bash
96
+ pnpm add postbound
97
+ ```
98
+
99
+ ```bash
100
+ npm install postbound
101
+ ```
102
+
103
+ Node.js 20 or later is required.
104
+
105
+ ### Quickstart
106
+
107
+ 1. Add and verify a sending domain in the Postbound portal, or with [`domains.create`](#domains).
108
+ 2. Create an API key and expose it as `POSTBOUND_API_KEY`.
109
+ 3. Send your first email.
110
+
111
+ ```ts
112
+ import { Postbound } from 'postbound';
113
+
114
+ const postbound = new Postbound(process.env.POSTBOUND_API_KEY);
115
+
116
+ const { data, error } = await postbound.emails.send({
117
+ from: 'Acme <hello@acme.com>',
118
+ to: 'ada@example.org',
119
+ subject: 'Welcome to Acme',
120
+ html: '<h1>Welcome, Ada</h1><p>Your account is ready.</p>',
121
+ });
122
+
123
+ if (error) {
124
+ console.error(error.name, error.message);
125
+ } else {
126
+ console.log('Queued', data.id);
127
+ }
128
+ ```
129
+
130
+ The `from` address must belong to a domain that is verified and has sending enabled. Otherwise the API rejects the request with a `validation_error` and a `403` status.
131
+
132
+ ### What it covers
133
+
134
+ | Client | What you can do |
135
+ | ---------------------------- | ---------------------------------------------------------------- |
136
+ | `postbound.emails` | Send, schedule, reschedule, cancel, retrieve, and list emails |
137
+ | `postbound.batch` | Send up to 100 emails in one request |
138
+ | `postbound.emails.receiving` | Read inbound mail and its attachments |
139
+ | `postbound.domains` | Add, verify, configure, and remove sending and receiving domains |
140
+ | `postbound.apiKeys` | Create, list, and delete API keys |
141
+ | `postbound.audiences` | Manage mailing lists |
142
+ | `postbound.contacts` | Manage the contacts in an audience |
143
+ | `postbound.webhooks` | Manage webhooks, send test deliveries, and verify signatures |
144
+
145
+ Billing, workspaces, members, sign-in, and usage metrics are portal endpoints and are not part of the SDK.
146
+
147
+ ### Handling responses
148
+
149
+ No method throws on an API or network error. Each one resolves to an object with three fields:
150
+
151
+ | Field | Type | Meaning |
152
+ | --------- | ------------------------------------- | ------------------------------------------------------ |
153
+ | `data` | the resource, or `null` | Set when the request succeeded |
154
+ | `error` | [`ErrorResponse`](#errors), or `null` | Set when the request failed |
155
+ | `headers` | `Record<string, string>`, or `null` | Response headers. `null` when no response was received |
156
+
157
+ Exactly one of `data` and `error` is set, and TypeScript narrows both:
158
+
159
+ ```ts
160
+ const { data, error } = await postbound.domains.get('domain-id');
161
+
162
+ if (error) {
163
+ throw new Error(`${error.name}: ${error.message}`);
164
+ }
165
+
166
+ console.log(data.status);
167
+ ```
168
+
169
+ The only thing that rejects is a request you cancel with an `AbortSignal`, which rejects with the abort reason. Methods that return no body, such as `apiKeys.remove`, resolve with `data: {}`.
170
+
171
+ ### Emails
172
+
173
+ `emails.send` and `emails.create` are the same method.
174
+
175
+ ```ts
176
+ const { data, error } = await postbound.emails.send({
177
+ from: 'Acme <hello@acme.com>',
178
+ to: ['ada@example.org', 'grace@example.org'],
179
+ cc: 'team@acme.com',
180
+ bcc: ['archive@acme.com'],
181
+ replyTo: 'support@acme.com',
182
+ subject: 'Your March invoice',
183
+ html: '<p>Your invoice is attached.</p>',
184
+ text: 'Your invoice is attached.',
185
+ headers: { 'X-Entity-Ref-ID': 'inv_123' },
186
+ tags: [{ name: 'category', value: 'invoice' }],
187
+ });
188
+ ```
189
+
190
+ | Option | Type | Notes |
191
+ | ------------- | ----------------------------------- | --------------------------------------------------------------- |
192
+ | `from` | `string` | Required. `email@acme.com` or `Name <email@acme.com>` |
193
+ | `to` | `string \| string[]` | Required |
194
+ | `subject` | `string` | Required |
195
+ | `html` | `string` | At least one of `html`, `text`, or `react` is required |
196
+ | `text` | `string` | Plain text version |
197
+ | `react` | `React.ReactNode` | Rendered to `html`. See [React Email](#react-email) |
198
+ | `cc` | `string \| string[]` | |
199
+ | `bcc` | `string \| string[]` | |
200
+ | `replyTo` | `string \| string[]` | Sent as the `Reply-To` header |
201
+ | `headers` | `Record<string, string>` | Custom headers. Reserved headers such as `Subject` are rejected |
202
+ | `tags` | `{ name: string; value: string }[]` | Returned in webhooks and when you retrieve the email |
203
+ | `attachments` | [`Attachment[]`](#attachments) | |
204
+ | `scheduledAt` | `string` | See [Scheduling](#scheduling) |
205
+
206
+ The response is `{ id: string }`. The email is queued, not delivered. Follow delivery with [webhooks](#webhooks) or [`emails.get`](#retrieving-and-listing).
207
+
208
+ #### Attachments
209
+
210
+ Give each attachment either `content` or `path`, never both.
211
+
212
+ ```ts
213
+ import { readFile } from 'node:fs/promises';
214
+
215
+ await postbound.emails.send({
216
+ from: 'Acme <hello@acme.com>',
217
+ to: 'ada@example.org',
218
+ subject: 'Your invoice',
219
+ html: '<p>See attached.</p><img src="cid:logo" />',
220
+ attachments: [
221
+ {
222
+ filename: 'invoice.pdf',
223
+ content: await readFile('invoice.pdf'),
224
+ },
225
+ {
226
+ filename: 'logo.png',
227
+ content: await readFile('logo.png'),
228
+ contentType: 'image/png',
229
+ contentId: 'logo',
230
+ },
231
+ {
232
+ filename: 'terms.pdf',
233
+ path: 'https://acme.com/legal/terms.pdf',
234
+ },
235
+ ],
236
+ });
237
+ ```
238
+
239
+ | Field | Type | Notes |
240
+ | ------------- | --------------------------------------------------------- | ------------------------------------------------------------------------------ |
241
+ | `content` | `Buffer`, `Uint8Array`, `ArrayBuffer`, or base64 `string` | Binary values are base64 encoded for you |
242
+ | `path` | `string` | An `http` or `https` URL that Postbound fetches |
243
+ | `filename` | `string` | Required with `content`. Optional with `path` when the URL ends in a file name |
244
+ | `contentType` | `string` | Inferred from the file name when omitted |
245
+ | `contentId` | `string` | Makes the attachment inline. Reference it with `cid:` in your HTML |
246
+
247
+ #### React Email
248
+
249
+ Install [`@react-email/render`](https://www.npmjs.com/package/@react-email/render), an optional peer dependency, and pass a component as `react`.
250
+
251
+ ```tsx
252
+ import { Postbound } from 'postbound';
253
+ import { WelcomeEmail } from './emails/welcome';
254
+
255
+ const postbound = new Postbound();
256
+
257
+ await postbound.emails.send({
258
+ from: 'Acme <hello@acme.com>',
259
+ to: 'ada@example.org',
260
+ subject: 'Welcome to Acme',
261
+ react: <WelcomeEmail name="Ada" />,
262
+ });
263
+ ```
264
+
265
+ When `react` is set, its rendered output replaces `html`. If the package is missing, the call throws an error that names what to install.
266
+
267
+ #### Scheduling
268
+
269
+ `scheduledAt` takes an ISO 8601 timestamp or a relative expression such as `in 30 minutes`, `in 1 hour`, or `in 3 days`.
270
+
271
+ ```ts
272
+ await postbound.emails.send({
273
+ from: 'Acme <hello@acme.com>',
274
+ to: 'ada@example.org',
275
+ subject: 'Your trial ends tomorrow',
276
+ text: 'Upgrade to keep your data.',
277
+ scheduledAt: 'in 2 hours',
278
+ });
279
+
280
+ await postbound.emails.update({
281
+ id: 'email-id',
282
+ scheduledAt: '2026-11-14T09:00:00Z',
283
+ });
284
+
285
+ await postbound.emails.cancel('email-id');
286
+ ```
287
+
288
+ A time in the past sends the email immediately, and by default emails can be scheduled up to 30 days ahead. `update` and `cancel` return `{ object: 'email', id }`, and fail with `invalid_state` once the email has been sent.
289
+
290
+ #### Idempotency
291
+
292
+ Pass an `idempotencyKey` to make a send safe to retry. Postbound stores the response for the key, 24 hours by default, and replays it for an identical request instead of sending again.
293
+
294
+ ```ts
295
+ await postbound.emails.send(
296
+ {
297
+ from: 'Acme <hello@acme.com>',
298
+ to: 'ada@example.org',
299
+ subject: 'Your receipt',
300
+ text: 'Thanks for your order.',
301
+ },
302
+ { idempotencyKey: `receipt-${order.id}` },
303
+ );
304
+ ```
305
+
306
+ - A replayed response has the header `Idempotent-Replayed: true`, available as `idempotent-replayed` in `headers`.
307
+ - Reusing a key with a different body fails with `invalid_idempotent_request`.
308
+ - Reusing a key while the first request is still running fails with `concurrent_idempotent_requests`.
309
+ - Keys can be up to 256 characters.
310
+
311
+ The API only deduplicates `emails.send`, `emails.create`, `batch.send`, and `batch.create`.
312
+
313
+ #### Batch sending
314
+
315
+ Send up to 100 emails in one request. If any email is invalid, none are sent, and the error message names the failing index, such as `emails[3]: Missing "subject" field.`
316
+
317
+ ```ts
318
+ const { data, error } = await postbound.batch.send(
319
+ [
320
+ {
321
+ from: 'Acme <hello@acme.com>',
322
+ to: 'ada@example.org',
323
+ subject: 'Hello Ada',
324
+ html: '<p>Hi Ada</p>',
325
+ },
326
+ {
327
+ from: 'Acme <hello@acme.com>',
328
+ to: 'grace@example.org',
329
+ subject: 'Hello Grace',
330
+ react: <Greeting name="Grace" />,
331
+ },
332
+ ],
333
+ { idempotencyKey: 'welcome-batch-42' },
334
+ );
335
+
336
+ if (!error) {
337
+ console.log(data.data.map((email) => email.id));
338
+ }
339
+ ```
340
+
341
+ Each item accepts the same options as `emails.send`, except `attachments` and `scheduledAt`. `data.data` lists the IDs in the order you sent them. `batch.create` is an alias of `batch.send`.
342
+
343
+ #### Retrieving and listing
344
+
345
+ ```ts
346
+ const { data: email } = await postbound.emails.get('email-id');
347
+
348
+ console.log(email?.last_event);
349
+ console.log(email?.events);
350
+
351
+ const { data: page } = await postbound.emails.list({
352
+ limit: 50,
353
+ status: 'bounced',
354
+ q: 'invoice',
355
+ });
356
+ ```
357
+
358
+ `emails.get` returns the email plus its delivery timeline in `events`, each with a `type`, `occurred_at`, and `metadata`. Event types are `queued`, `scheduled`, `sent`, `delivered`, `delivery_delayed`, `bounced`, `complained`, `opened`, `clicked`, `failed`, and `canceled`.
359
+
360
+ | List option | Type | Notes |
361
+ | -------------------------- | ------------ | ------------------------------------ |
362
+ | `status` | `EmailEvent` | Only emails whose last event matches |
363
+ | `q` | `string` | Search text, up to 200 characters |
364
+ | `limit`, `after`, `before` | | See [Pagination](#pagination) |
365
+
366
+ List items leave out `html`, `text`, `tags`, and `events`. Call `emails.get` for those.
367
+
368
+ ### Receiving email
369
+
370
+ Postbound receives mail for your domains and exposes it through the API. Receiving uses a full-access API key.
371
+
372
+ 1. Turn on receiving for a verified domain:
373
+
374
+ ```ts
375
+ await postbound.domains.update({
376
+ id: 'domain-id',
377
+ capabilities: { receiving: 'enabled' },
378
+ });
379
+ ```
380
+
381
+ 2. Publish the `Receiving` MX record that now appears in the domain's `records`, then verify:
382
+
383
+ ```ts
384
+ const { data: domain } = await postbound.domains.get('domain-id');
385
+
386
+ console.log(domain?.records.filter((record) => record.record === 'Receiving'));
387
+
388
+ await postbound.domains.verify('domain-id');
389
+ ```
390
+
391
+ 3. Read what arrives:
392
+
393
+ ```ts
394
+ const { data: inbox } = await postbound.emails.receiving.list({ limit: 20 });
395
+
396
+ const { data: email } = await postbound.emails.receiving.get('received-id');
397
+
398
+ console.log(email?.from, email?.subject, email?.text);
399
+ console.log(email?.authentication);
400
+ ```
401
+
402
+ `email.authentication` reports `spf`, `dkim`, and `dmarc`, each one of `pass`, `fail`, `gray`, `processing_failed`, or `unknown`.
403
+
404
+ By default, `cid:` references in `html` are replaced with `data:` URIs when the inline parts total 2 MB or less. Ask for the original references with `html_format`, and each one then matches the `content_id` of an attachment. The `html_format` on the response says which format you received.
405
+
406
+ ```ts
407
+ const { data } = await postbound.emails.receiving.get('received-id', {
408
+ html_format: 'cid',
409
+ });
410
+ ```
411
+
412
+ Attachments and the raw message are returned as signed download URLs:
413
+
414
+ ```ts
415
+ const { data: attachments } = await postbound.emails.receiving.attachments.list(
416
+ {
417
+ emailId: 'received-id',
418
+ },
419
+ );
420
+
421
+ const { data: attachment } = await postbound.emails.receiving.attachments.get({
422
+ emailId: 'received-id',
423
+ id: 'attachment-id',
424
+ });
425
+
426
+ const response = await fetch(attachment!.download_url);
427
+ const bytes = Buffer.from(await response.arrayBuffer());
428
+ ```
429
+
430
+ `download_url` and `raw.download_url` are valid for one hour and need no `Authorization` header, so you can hand them to a browser or another service. Ask for a fresh one when it expires. To react to inbound mail as it arrives, subscribe a webhook to [`email.received`](#events).
431
+
432
+ ### Domains
433
+
434
+ ```ts
435
+ const { data: domain } = await postbound.domains.create({
436
+ name: 'acme.com',
437
+ region: 'us-east-1',
438
+ customReturnPath: 'send',
439
+ });
440
+
441
+ for (const record of domain?.records ?? []) {
442
+ console.log(record.record, record.type, record.name, record.value);
443
+ }
444
+ ```
445
+
446
+ `create` returns the DNS records to publish:
447
+
448
+ | Record | Type | Purpose |
449
+ | ----------- | ----------- | ---------------------------------------------------------------- |
450
+ | `Ownership` | `TXT` | Proves you control the domain. Verification waits on this record |
451
+ | `DKIM` | `TXT` | Signs outgoing mail |
452
+ | `SPF` | `MX`, `TXT` | Authorizes Postbound to send for the return path |
453
+ | `Receiving` | `MX` | Only listed when receiving is enabled |
454
+
455
+ A domain is `not_started`, `pending`, `verified`, or `failed`. After you publish the records, ask Postbound to check again:
456
+
457
+ ```ts
458
+ await postbound.domains.verify('domain-id');
459
+ ```
460
+
461
+ `verify` returns `{ object: 'domain', id }` straight away. Read `status` with `domains.get`, or subscribe to the `domain.verified` and `domain.failed` [events](#events).
462
+
463
+ ```ts
464
+ await postbound.domains.update({
465
+ id: 'domain-id',
466
+ openTracking: true,
467
+ clickTracking: true,
468
+ tls: 'enforced',
469
+ capabilities: { sending: 'enabled', receiving: 'enabled' },
470
+ });
471
+
472
+ const { data: domains } = await postbound.domains.list();
473
+
474
+ await postbound.domains.remove('domain-id');
475
+ ```
476
+
477
+ | Update option | Type |
478
+ | --------------- | ---------------------------------------------------------- |
479
+ | `openTracking` | `boolean` |
480
+ | `clickTracking` | `boolean` |
481
+ | `tls` | `'opportunistic' \| 'enforced'` |
482
+ | `capabilities` | `{ sending?, receiving? }`, each `'enabled' \| 'disabled'` |
483
+
484
+ Only the fields you pass are changed. At least one of sending and receiving must stay enabled.
485
+
486
+ ### API keys
487
+
488
+ ```ts
489
+ const { data, error } = await postbound.apiKeys.create({
490
+ name: 'Production',
491
+ permission: 'sending_access',
492
+ domainId: 'domain-id',
493
+ });
494
+
495
+ if (!error) {
496
+ console.log(data.token);
497
+ }
498
+
499
+ const { data: keys } = await postbound.apiKeys.list();
500
+
501
+ await postbound.apiKeys.remove('key-id');
502
+ ```
503
+
504
+ > [!IMPORTANT]
505
+ > The `token` is returned only once, when the key is created. Store it in your secrets manager straight away. Later reads only expose `token_prefix`.
506
+
507
+ | Permission | Can do |
508
+ | ---------------- | --------------------------------------------------- |
509
+ | `full_access` | Everything in this SDK. The default |
510
+ | `sending_access` | Send email with `emails.send` and `batch.send` only |
511
+
512
+ A `sending_access` key can be locked to one domain with `domainId`, and sending from any other domain fails. Any other call with a sending key fails with `restricted_api_key`. Use sending keys in application servers and keep full-access keys for management tasks.
513
+
514
+ ### Audiences and contacts
515
+
516
+ ```ts
517
+ const { data: audience } = await postbound.audiences.create({
518
+ name: 'Newsletter',
519
+ });
520
+
521
+ const { data: contact } = await postbound.contacts.create({
522
+ audienceId: audience!.id,
523
+ email: 'ada@example.org',
524
+ firstName: 'Ada',
525
+ lastName: 'Lovelace',
526
+ unsubscribed: false,
527
+ });
528
+
529
+ await postbound.audiences.get('audience-id');
530
+ await postbound.audiences.list();
531
+ await postbound.audiences.remove('audience-id');
532
+ ```
533
+
534
+ Look contacts up by `id` or by `email`, not both:
535
+
536
+ ```ts
537
+ await postbound.contacts.get({
538
+ audienceId: 'audience-id',
539
+ email: 'ada@example.org',
540
+ });
541
+
542
+ await postbound.contacts.update({
543
+ audienceId: 'audience-id',
544
+ id: 'contact-id',
545
+ unsubscribed: true,
546
+ });
547
+
548
+ await postbound.contacts.remove({
549
+ audienceId: 'audience-id',
550
+ email: 'ada@example.org',
551
+ });
552
+
553
+ const { data: contacts } = await postbound.contacts.list({
554
+ audienceId: 'audience-id',
555
+ limit: 100,
556
+ });
557
+ ```
558
+
559
+ Passing neither `id` nor `email` resolves with a `missing_required_field` error and sends no request. Creating a contact that already exists in the audience fails with `contact_already_exists`.
560
+
561
+ ### Webhooks
562
+
563
+ Webhooks push delivery, inbound mail, and domain events to your server.
564
+
565
+ ```ts
566
+ const { data, error } = await postbound.webhooks.create({
567
+ url: 'https://acme.com/hooks/postbound',
568
+ events: ['email.delivered', 'email.bounced', 'email.received'],
569
+ });
570
+
571
+ if (!error) {
572
+ console.log(data.id);
573
+ console.log(data.signing_secret);
574
+ }
575
+ ```
576
+
577
+ | Option | Type | Notes |
578
+ | --------- | -------------------------------- | ------------------------------------------------ |
579
+ | `url` | `string` | Required. Must be `https` and publicly reachable |
580
+ | `events` | `WebhookEvent[]` | Required. At least one |
581
+ | `type` | `'http' \| 'discord' \| 'teams'` | Defaults to `http` |
582
+ | `enabled` | `boolean` | Defaults to `true` |
583
+
584
+ An account can have up to 20 webhooks. `http` webhooks send signed JSON and have a `signing_secret` that starts with `whsec_`, returned by `create` and `get`. `discord` and `teams` webhooks post a formatted chat message instead, so they have no signing secret. `type` cannot be changed after creation.
585
+
586
+ ```ts
587
+ await postbound.webhooks.create({
588
+ type: 'discord',
589
+ url: 'https://discord.com/api/webhooks/123456789/abcdef',
590
+ events: ['email.bounced', 'email.complained', 'domain.failed'],
591
+ });
592
+
593
+ await postbound.webhooks.get('webhook-id');
594
+ await postbound.webhooks.list();
595
+ await postbound.webhooks.update('webhook-id', { enabled: false });
596
+ await postbound.webhooks.remove('webhook-id');
597
+
598
+ const { data: test } = await postbound.webhooks.test('webhook-id');
599
+
600
+ console.log(test?.success, test?.status_code, test?.error);
601
+ ```
602
+
603
+ Each webhook reports `last_delivery_status`, which is `success`, `failed`, or `null` when nothing has been delivered. Failed deliveries are retried with backoff.
604
+
605
+ #### Events
606
+
607
+ | Event | Fired when |
608
+ | ------------------------ | -------------------------------------------------------- |
609
+ | `email.sent` | The email left Postbound for the recipient's mail server |
610
+ | `email.delivered` | The recipient's mail server accepted it |
611
+ | `email.delivery_delayed` | Delivery hit a temporary problem and will be retried |
612
+ | `email.bounced` | The recipient's mail server rejected it permanently |
613
+ | `email.complained` | The recipient marked it as spam |
614
+ | `email.opened` | The recipient opened it |
615
+ | `email.clicked` | The recipient clicked a link |
616
+ | `email.failed` | Postbound gave up sending it |
617
+ | `email.received` | A message arrived on one of your receiving domains |
618
+ | `domain.verified` | A domain finished verification |
619
+ | `domain.failed` | Domain verification failed or expired |
620
+
621
+ #### Verifying deliveries
622
+
623
+ Always verify a delivery before you trust it. `webhooks.verify` checks the signature and timestamp, then returns the parsed event. It throws if the signature is missing, invalid, or too old. Verify against the **raw** request body, because a parsed and re-serialized body will not match the signature.
624
+
625
+ ```ts
626
+ import express from 'express';
627
+ import { Postbound } from 'postbound';
628
+
629
+ const postbound = new Postbound();
630
+ const app = express();
631
+
632
+ app.post(
633
+ '/hooks/postbound',
634
+ express.text({ type: 'application/json' }),
635
+ (req, res) => {
636
+ let event;
637
+
638
+ try {
639
+ event = postbound.webhooks.verify({
640
+ payload: req.body,
641
+ headers: {
642
+ id: req.header('webhook-id') ?? '',
643
+ timestamp: req.header('webhook-timestamp') ?? '',
644
+ signature: req.header('webhook-signature') ?? '',
645
+ },
646
+ webhookSecret: process.env.POSTBOUND_WEBHOOK_SECRET ?? '',
647
+ });
648
+ } catch {
649
+ res.sendStatus(400);
650
+ return;
651
+ }
652
+
653
+ switch (event.type) {
654
+ case 'email.bounced':
655
+ console.log('Bounced', event.data.email_id, event.data.metadata);
656
+ break;
657
+ case 'email.received':
658
+ console.log('Inbound', event.data.email_id, event.data.subject);
659
+ break;
660
+ case 'domain.verified':
661
+ console.log('Verified', event.data.name);
662
+ break;
663
+ }
664
+
665
+ res.sendStatus(200);
666
+ },
667
+ );
668
+ ```
669
+
670
+ Respond with a `2xx` status quickly and do slow work afterwards. Any other status counts as a failed delivery and is retried. A retry carries the same `webhook-id`, so use it to ignore duplicates.
671
+
672
+ With Next.js route handlers, read the payload with `await request.text()`:
673
+
674
+ ```ts
675
+ import { Postbound } from 'postbound';
676
+
677
+ const postbound = new Postbound();
678
+
679
+ export async function POST(request: Request) {
680
+ const payload = await request.text();
681
+
682
+ try {
683
+ const event = postbound.webhooks.verify({
684
+ payload,
685
+ headers: {
686
+ id: request.headers.get('webhook-id') ?? '',
687
+ timestamp: request.headers.get('webhook-timestamp') ?? '',
688
+ signature: request.headers.get('webhook-signature') ?? '',
689
+ },
690
+ webhookSecret: process.env.POSTBOUND_WEBHOOK_SECRET ?? '',
691
+ });
692
+
693
+ console.log(event.type);
694
+ return new Response(null, { status: 200 });
695
+ } catch {
696
+ return new Response(null, { status: 400 });
697
+ }
698
+ }
699
+ ```
700
+
701
+ #### Event payloads
702
+
703
+ Every delivery has a `type`, a `created_at`, and a `data` object. The `type` field narrows `data` in TypeScript.
704
+
705
+ `email.*` events:
706
+
707
+ ```json
708
+ {
709
+ "type": "email.bounced",
710
+ "created_at": "2026-11-12T10:00:02Z",
711
+ "data": {
712
+ "email_id": "0198f2a4-5b1c-7d3e-9a10-2f4c8b6d1e07",
713
+ "from": "Acme <hello@acme.com>",
714
+ "to": ["ada@example.org"],
715
+ "subject": "Welcome to Acme",
716
+ "tags": [{ "name": "category", "value": "welcome" }],
717
+ "created_at": "2026-11-12T10:00:00Z",
718
+ "metadata": { "reason": "mailbox full" }
719
+ }
720
+ }
721
+ ```
722
+
723
+ `metadata` is present when the event carries extra detail, such as a bounce reason.
724
+
725
+ `email.received`:
726
+
727
+ ```json
728
+ {
729
+ "type": "email.received",
730
+ "created_at": "2026-11-12T10:00:01Z",
731
+ "data": {
732
+ "email_id": "0198f2a4-9c20-7a11-8b3d-5e7f0a1c2d44",
733
+ "created_at": "2026-11-12T10:00:00Z",
734
+ "from": "Ada <ada@example.org>",
735
+ "to": ["support@acme.com"],
736
+ "cc": [],
737
+ "bcc": [],
738
+ "received_for": ["support@acme.com"],
739
+ "message_id": "<abc@example.org>",
740
+ "subject": "Hello",
741
+ "attachments": [
742
+ {
743
+ "id": "0198f2a4-9c21-7b02-a4c6-1d3e5f7a9b20",
744
+ "filename": "invoice.pdf",
745
+ "content_type": "application/pdf",
746
+ "content_disposition": "attachment",
747
+ "content_id": null
748
+ }
749
+ ]
750
+ }
751
+ }
752
+ ```
753
+
754
+ The payload never includes message bodies or attachment content. Fetch them with [`emails.receiving.get`](#receiving-email).
755
+
756
+ `domain.verified` and `domain.failed`:
757
+
758
+ ```json
759
+ {
760
+ "type": "domain.verified",
761
+ "created_at": "2026-11-12T10:05:00Z",
762
+ "data": {
763
+ "domain_id": "0198f2a3-0a4e-7c55-92d1-6b8e4f0a3c19",
764
+ "name": "acme.com",
765
+ "status": "verified",
766
+ "region": "us-east-1"
767
+ }
768
+ }
769
+ ```
770
+
771
+ `webhook.test`, sent by `webhooks.test`:
772
+
773
+ ```json
774
+ {
775
+ "type": "webhook.test",
776
+ "created_at": "2026-11-12T10:10:00Z",
777
+ "data": {
778
+ "message": "This is a test message from Postbound. Your webhook is configured correctly."
779
+ }
780
+ }
781
+ ```
782
+
783
+ ### Pagination
784
+
785
+ Every list method uses cursor pagination and returns `{ object: 'list', has_more, data }`.
786
+
787
+ | Option | Type | Notes |
788
+ | -------- | -------- | ------------------------------------------------------------ |
789
+ | `limit` | `number` | 1 to 100. Defaults to 20 |
790
+ | `after` | `string` | Return items after this ID. Cannot be combined with `before` |
791
+ | `before` | `string` | Return items before this ID. Cannot be combined with `after` |
792
+
793
+ TypeScript stops you from passing both `after` and `before`. To walk every page:
794
+
795
+ ```ts
796
+ async function* allDomains() {
797
+ let after: string | undefined;
798
+
799
+ while (true) {
800
+ const { data, error } = await postbound.domains.list({ limit: 100, after });
801
+
802
+ if (error) {
803
+ throw new Error(error.message);
804
+ }
805
+
806
+ yield* data.data;
807
+
808
+ if (!data.has_more) {
809
+ return;
810
+ }
811
+
812
+ after = data.data.at(-1)?.id;
813
+ }
814
+ }
815
+
816
+ for await (const domain of allDomains()) {
817
+ console.log(domain.name);
818
+ }
819
+ ```
820
+
821
+ Contacts and received-email attachments also need their parent ID: `contacts.list({ audienceId })` and `emails.receiving.attachments.list({ emailId })`.
822
+
823
+ ### Request options
824
+
825
+ The last argument of every method sets per-request options.
826
+
827
+ ```ts
828
+ await postbound.emails.get('email-id', {
829
+ headers: { 'X-Trace-Id': 'trace-123' },
830
+ signal: AbortSignal.timeout(5_000),
831
+ });
832
+ ```
833
+
834
+ | Option | Type | Available on | Notes |
835
+ | ---------------- | ------------- | ------------------- | -------------------------------------- |
836
+ | `headers` | `HeadersInit` | every method | Merged over the defaults |
837
+ | `signal` | `AbortSignal` | every method | Aborting rejects with the abort reason |
838
+ | `idempotencyKey` | `string` | methods that `POST` | Sent as the `Idempotency-Key` header |
839
+
840
+ The client sends `Authorization: Bearer <key>`, `Content-Type: application/json`, and a `User-Agent`. Custom headers can override any of them.
841
+
842
+ ### Errors
843
+
844
+ A failed call returns an `ErrorResponse`:
845
+
846
+ ```ts
847
+ {
848
+ name: ErrorCode;
849
+ message: string;
850
+ statusCode: number | null;
851
+ request_id?: string;
852
+ }
853
+ ```
854
+
855
+ `statusCode` is `null` when no response was received. Include `request_id` when you contact support.
856
+
857
+ | `name` | Status | Meaning |
858
+ | --------------------------------- | -------------- | ----------------------------------------------------------------------------------------- |
859
+ | `missing_api_key` | 401 | No `Authorization` header was sent |
860
+ | `invalid_api_key` | 403 | The key is malformed or does not exist |
861
+ | `restricted_api_key` | 401 | A `sending_access` key was used for something other than sending |
862
+ | `validation_error` | 422, 403, 413 | A field is invalid, the sender domain is unverified or disabled, or the body is too large |
863
+ | `missing_required_field` | 422 | A required field is missing |
864
+ | `invalid_parameter` | 422 | A field has the wrong value or format |
865
+ | `invalid_from_address` | 422 | `from` is not a valid address |
866
+ | `invalid_scheduled_date` | 422 | `scheduledAt` is malformed or too far ahead |
867
+ | `invalid_attachment` | 422 | An attachment is malformed, too large, or blocked |
868
+ | `invalid_json` | 400 | The request body is not valid JSON |
869
+ | `forbidden` | 403 | You are not allowed to do this |
870
+ | `not_found` | 404 | The resource does not exist or belongs to another account |
871
+ | `method_not_allowed` | 405 | The endpoint does not support that method |
872
+ | `invalid_state` | 409 | The resource is not in a state that allows this, such as cancelling a sent email |
873
+ | `domain_already_exists` | 409 | The domain is already registered |
874
+ | `contact_already_exists` | 409 | The contact is already in the audience |
875
+ | `verification_conflict` | 409 | A verification for the domain is already in progress |
876
+ | `invalid_idempotent_request` | 409 | The idempotency key was used with a different payload |
877
+ | `concurrent_idempotent_requests` | 409 | A request with the same idempotency key is still running |
878
+ | `invalid_download_link` | 403 | A signed download URL is invalid or expired |
879
+ | `rate_limit_exceeded` | 429 | Too many requests. See [Rate limits](#rate-limits) |
880
+ | `internal_server_error` | 500 | Something went wrong on our side |
881
+ | `domain_verification_unavailable` | 502 | Domain verification is temporarily unavailable. Try again later |
882
+ | `application_error` | any, or `null` | The SDK could not reach the API or could not read its response |
883
+
884
+ ### Rate limits
885
+
886
+ Requests are rate limited per account, so every API key on an account shares one budget. Every response carries `RateLimit-Limit` (the burst size), `RateLimit-Remaining`, and `RateLimit-Reset` headers. When you go over, the call fails with `rate_limit_exceeded`, and `Retry-After` says how many seconds to wait.
887
+
888
+ ```ts
889
+ import type { CreateEmailOptions } from 'postbound';
890
+
891
+ async function sendWithRetry(
892
+ payload: CreateEmailOptions,
893
+ key: string,
894
+ attempts = 3,
895
+ ) {
896
+ for (let attempt = 1; ; attempt++) {
897
+ const result = await postbound.emails.send(payload, {
898
+ idempotencyKey: key,
899
+ });
900
+
901
+ if (result.error?.name !== 'rate_limit_exceeded' || attempt === attempts) {
902
+ return result;
903
+ }
904
+
905
+ const wait = Number(result.headers?.['retry-after'] ?? 1);
906
+ await new Promise((resolve) => setTimeout(resolve, wait * 1000));
907
+ }
908
+ }
909
+ ```
910
+
911
+ Header names are lower-cased in `headers`, and reusing the idempotency key makes each retry safe.
912
+
913
+ ### Limits
914
+
915
+ | Limit | Value |
916
+ | ----------------------------------------------------- | -------------------------------------------------- |
917
+ | Recipients per email (`to`, `cc`, and `bcc` combined) | 50 |
918
+ | Emails per batch | 100 |
919
+ | Subject length | 998 characters |
920
+ | Attachment content per email | 40 MB |
921
+ | Custom headers per email | 50 |
922
+ | Tags per email | 20 |
923
+ | Tag name and value | 256 characters of `A-Z a-z 0-9 _ -` |
924
+ | Scheduling horizon | 30 days by default |
925
+ | Idempotency key | 256 characters, remembered for 24 hours by default |
926
+ | Webhooks per account | 20 |
927
+ | Domain name | 253 characters |
928
+ | Request body, sending | 64 MB |
929
+ | Request body, everything else | 2 MB |
930
+ | Signed download URLs | Valid for 1 hour |
931
+
932
+ Some values are configurable on the server and can differ between deployments.
933
+
934
+ ### TypeScript
935
+
936
+ The package ships its own declarations, and every option and response type is exported from the root.
937
+
938
+ ```ts
939
+ import type {
940
+ CreateEmailOptions,
941
+ CreateEmailResponseSuccess,
942
+ Domain,
943
+ EmailEvent,
944
+ ErrorResponse,
945
+ Response,
946
+ WebhookEvent,
947
+ WebhookEventPayload,
948
+ } from 'postbound';
949
+ ```
950
+
951
+ Type names follow one pattern per method: `CreateEmailOptions` is what you pass in, `CreateEmailResponseSuccess` is the `data` you get back, and `CreateEmailResponse` is `Response<CreateEmailResponseSuccess>`, the full `{ data, error, headers }`. Discriminate webhook events by `type`:
952
+
953
+ ```ts
954
+ import type { WebhookEventPayload } from 'postbound';
955
+
956
+ function handle(event: WebhookEventPayload) {
957
+ if (event.type === 'email.received') {
958
+ return event.data.attachments.length;
959
+ }
960
+
961
+ if (event.type === 'domain.failed') {
962
+ return event.data.name;
963
+ }
964
+ }
965
+ ```
966
+
967
+ ### Migrating from Resend
968
+
969
+ Postbound's API follows Resend's request and error shapes, so most code needs only a rename.
970
+
971
+ ```diff
972
+ - import { Resend } from 'resend';
973
+ - const resend = new Resend(process.env.RESEND_API_KEY);
974
+ + import { Postbound } from 'postbound';
975
+ + const postbound = new Postbound(process.env.POSTBOUND_API_KEY);
976
+
977
+ - await resend.emails.send({ ... });
978
+ + await postbound.emails.send({ ... });
979
+ ```
980
+
981
+ What stays the same:
982
+
983
+ - The `{ data, error, headers }` response envelope and the `ErrorResponse` shape
984
+ - `emails`, `batch`, `domains`, `apiKeys`, `webhooks`, `emails.receiving`, and `emails.receiving.attachments`
985
+ - `audiences` and `contacts`, including looking up a contact by `id` or `email`
986
+ - Options such as `replyTo`, `scheduledAt`, `tags`, `attachments`, `react`, and `idempotencyKey`
987
+ - `webhooks.verify` with `payload`, `headers`, and `webhookSecret`
988
+ - Cursor pagination with `limit`, `after`, and `before`
989
+
990
+ What differs:
991
+
992
+ | Resend | Postbound |
993
+ | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
994
+ | `RESEND_API_KEY`, `re_` keys | `POSTBOUND_API_KEY`, `pb_` keys |
995
+ | `RESEND_BASE_URL` | `POSTBOUND_BASE_URL` |
996
+ | `segments`, `topics`, `broadcasts`, `templates`, `automations`, `events`, `logs`, `inboxes`, `suppressions`, `usage` | Not available |
997
+ | `contacts` without an audience | Contacts always belong to an audience, so pass `audienceId` |
998
+ | `emails.attachments`, `emails.share`, `emails.metrics`, `emails.receiving.forward` | Not available |
999
+ | `batch.send(payload, { batchValidation })` | Batches are always validated strictly, and any invalid email rejects the whole batch |
1000
+ | `webhooks.rotateSigningSecret`, `webhooks.events` | Not available. Use `webhooks.test` to check an endpoint |
1001
+ | `topicId`, `template` on `emails.send` | Not available |
1002
+ | Webhook event `tags` as an object | `tags` is a `{ name, value }[]` array |
1003
+ | Domain `records[].record` values | `Ownership`, `DKIM`, `SPF`, and `Receiving` |
1004
+
1005
+ ## Notes
1006
+
1007
+ - Each resource lives in its own folder under `src/` with a class and an `interfaces.ts`. Shared types and helpers live in `src/common/`.
1008
+ - Request options use camelCase and are mapped to the API's snake_case inside the resource classes. Response types stay snake_case, exactly as the API returns them.
1009
+ - Methods never throw on API errors. They return `{ data, error, headers }` through the client in `src/postbound.ts`. Do not add code that throws for a failed response.
1010
+ - The SDK follows the shapes of the Postbound API. If an endpoint, field, or error name changes there, update the types and resource here to match.
1011
+ - Do not add comments to source files. Prefer clear names and small functions.
1012
+ - If you add a resource, export its types from `src/index.ts` and document it under Usage.
1013
+ - Run `pnpm check` before opening a pull request. It runs the same checks as CI.
1014
+
1015
+ ## Committing changes
1016
+
1017
+ Please use https://www.conventionalcommits.org/en/v1.0.0/ when commiting any changes.
1018
+
1019
+ ```bash
1020
+ git add .
1021
+ git commit -m "your message"
1022
+ git push
1023
+ ```