---
title: Node.js SDK
description: 用 @billionsend/node 在 Node.js 和 TypeScript 里发送邮件、使用收件箱、验证 Webhook，覆盖全部 API 操作，内置重试与幂等键。
ai:
  exclude: true
---

`@billionsend/node` 是 BillionSend 面向 Node.js 和 TypeScript 的客户端。它覆盖 [API 参考](/docs/zh-hans/api-reference)里的全部操作：发送、域名、联系人、群发、模板、Webhook、带会话和草稿的收件箱、实时的收件箱事件，以及 Agent 注册。类型来自 API 的 OpenAPI 文档。源码在 GitHub 上的 [billionsend/billionsend-node](https://github.com/billionsend/billionsend-node)。

## 安装

需要 Node 18 或更高版本。这个包没有依赖，同时提供 ES 模块和 CommonJS。

```sh
npm install @billionsend/node
```

## 发送邮件

```ts
import { BillionSend } from "@billionsend/node";

const bs = new BillionSend(); // 读取 BILLIONSEND_API_KEY

const { data, error } = await bs.emails.send(
  {
    from: "Acme <hello@acme.dev>",
    to: ["success@simulator.amazonses.com"],
    subject: "Welcome to Acme",
    html: "<p>Glad you are here.</p>",
  },
  { idempotencyKey: "welcome/ana" },
);

if (error) console.error(error.statusCode, error.name, error.message, error.requestId);
else console.log(data.id);
```

`new BillionSend("bs_...")` 直接传入密钥；`new BillionSend({ apiKey, baseUrl, timeoutMs, maxRetries, fetch })` 设置其余选项。`BILLIONSEND_BASE_URL` 可以覆盖 API 地址。

## 幂等与重试

发送类方法（`emails.send`、`emails.batch`、回复和转发、`inboxes.send`、`inboxes.drafts.send`）总是会带上 `Idempotency-Key`。如果你没有传自己的 `idempotencyKey`，每次调用会得到一个新的随机密钥，它的重试沿用这个密钥，所以超时后的重试不会重复发送；你自己的密钥还能让另一个进程里的重复调用也保持安全。

值得重试的失败默认会重试两次（`maxRetries`）：429、5xx、超时、网络错误，以及同一个密钥的第一次请求仍在运行时返回的 `409 concurrent_idempotent_requests`。只有重复执行也安全的请求才会重试：读取、`PUT`、`DELETE` 和发送类方法。客户端按 `retry-after` 的要求等待，最长一分钟，其余情况按指数退避。

## 错误

方法从不抛出异常。每个方法都返回 `{ data, error, headers }`，且 `data` 和 `error` 恰好有一个有值。`error` 是 `BillionSendError`，按种类对应一个类：`ValidationError`（400、422）、`AuthenticationError`（401）、`PermissionDeniedError`（403）、`NotFoundError`（404）、`ConflictError`（409）、`RateLimitError`（429，`retryAfter` 以秒为单位）、`APIError`（5xx）、`APIConnectionError` 和 `APITimeoutError`（没有响应）。每个错误都带 `statusCode`、`name`（API 的错误名）、`message` 和 `requestId`；`requestId` 是响应的 `x-request-id`，也就是这个请求在控制台日志页面上的 id。

```ts
import { NotFoundError } from "@billionsend/node";

const { data, error } = await bs.emails.get(id);
if (error instanceof NotFoundError) return null;
if (error) throw error;
```

`listAll` 和事件流会抛出同样的错误，因为它们没法为每一项各返回一个结果。

## Agent 的收件箱

在[事件流](/docs/zh-hans/inboxes)上等待新邮件，读取它，并在它所在的会话里回复：

```ts
const inbox = "support@acme.dev";
const opened = await bs.inboxes.events.streamInbox(inbox, { types: "inbox.email.received" });
if (opened.error) throw opened.error;

for await (const item of opened.data) {
  if (item.event === "stream.gap") continue; // 事件可能有缺失：重新读取会话
  const { thread_id, email_id } = item.data.data;
  if (!thread_id || !email_id) continue;

  const email = await bs.inboxes.threads.emails.get(inbox, thread_id, email_id);
  if (email.error) throw email.error;

  await bs.inboxes.threads.emails.reply(
    inbox,
    thread_id,
    email_id,
    { text: await draftAnswer(email.data.text) },
    { idempotencyKey: `reply/${email_id}` },
  );
}
```

连接断开时，事件流会带着 `Last-Event-ID` 重新连接，并补上错过的事件，所以不会丢失任何事件；保留 `opened.data.lastEventId`，就能在之后的运行里用 `{ lastEventId }` 接着读。从 24 小时之前的位置恢复时，会收到一次 `stream.gap`。单个收件箱的事件流在该收件箱被删除或过期后结束；`bs.inboxes.events.stream()` 会跟随团队的所有收件箱。

## 验证 Webhook

`verifyWebhook` 用端点的 `whsec_` 密钥检查一次 [Webhook](/docs/zh-hans/concepts/webhooks) 投递的签名和时间戳，并返回解析后的事件。传入的请求体必须与收到时完全一致：

```ts
import { verifyWebhook, WebhookVerificationError } from "@billionsend/node";

try {
  const event = await verifyWebhook(await request.text(), request.headers, process.env.BILLIONSEND_WEBHOOK_SECRET);
  if (event.type === "email.bounced") {
    // ...
  }
} catch (error) {
  if (error instanceof WebhookVerificationError) return new Response(null, { status: 400 });
  throw error;
}
```

使用 Express 时，用 `express.raw({ type: "application/json" })` 读取请求体，再传入 `req.body` 和 `req.headers`。超过五分钟的投递会被拒绝（可用 `tolerance` 调整），密钥轮换期间，新旧两个密钥都能通过验证。

## Agent 注册

```ts
const signup = await new BillionSend().agent.signup({
  human_email: "owner@acme.dev",
  name: "Support agent",
});
if (signup.data) console.log(signup.data.inbox.email_address);
```

这个调用不需要 API 密钥；响应里带有新的密钥和收件箱。未认领的账号可以做什么，见 [Agent 注册](/docs/zh-hans/agent-signup)。
