---
title: Node.js SDK
description: 用 @billionsend/node 在 Node.js 和 TypeScript 中傳送郵件、操作收件匣、驗證 Webhook，涵蓋全部 API 操作，內建重試與冪等鍵。
ai:
  exclude: true
---

`@billionsend/node` 套件是 BillionSend 面向 Node.js 和 TypeScript 的用戶端。它涵蓋 [API 參考](/docs/zh-hant/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-hant/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-hant/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-hant/agent-signup)。
