---
title: Ruby SDK
description: 用 billionsend gem 在 Ruby 中傳送郵件、操作收件匣、驗證 Webhook，涵蓋全部 API 操作，內建重試與冪等鍵。
ai:
  exclude: true
---

`billionsend` gem 是 BillionSend 面向 Ruby 的用戶端。它涵蓋 [API 參考](/docs/zh-hant/api-reference)中的全部操作：傳送、網域、聯絡人、群發、範本、Webhook、含會話串與草稿的收件匣、即時的收件匣事件，以及 Agent 註冊。原始碼在 GitHub 上的 [billionsend/billionsend-ruby](https://github.com/billionsend/billionsend-ruby)。

## 安裝

需要 Ruby 3.1 或更新版本。這個 gem 沒有執行階段的相依套件：它使用標準函式庫中的 `net/http`、`json` 和 `openssl`。

```sh
gem install billionsend
```

在 Gemfile 中寫 `gem "billionsend"`。

## 傳送郵件

```ruby
require "billionsend"

client = BillionSend::Client.new # 讀取 BILLIONSEND_API_KEY

sent = client.emails.send({
  from: "Acme <hello@acme.dev>",
  to: ["success@simulator.amazonses.com"],
  subject: "Welcome to Acme",
  html: "<p>Glad you are here.</p>"
}, idempotency_key: "welcome/ana")

puts sent["id"]
```

`BillionSend::Client.new(api_key: "bs_...")` 直接傳入金鑰；`base_url:`、`timeout:`（每次嘗試的秒數，預設 60）、`max_retries:`、`default_headers:` 和 `transport:`（任何像 `BillionSend::NetHTTPTransport` 那樣回應 `call` 和 `open_stream` 的物件，用來經由你自己的 HTTP 堆疊傳送）設定其餘選項。`BILLIONSEND_BASE_URL` 可以覆寫 API 網址。

## 方法命名

每個操作都是一個方法，以它在 [API 參考](/docs/zh-hant/api-reference)中的 id 命名，以點分隔的路徑寫成以 snake_case 命名的資源鏈：`emails.send` 是 `client.emails.send`，`emails.receiving.attachments.list` 是 `client.emails.receiving.attachments.list`，`agent.claimEmail` 是 `client.agent.claim_email`。`emails.metrics` 是 `client.emails.metrics.call`，與 `.links`、`.countries` 和 `.clients` 並列。

方法依序接受路徑參數、放在大括號中的 Hash 形式的請求本文，然後是以關鍵字引數傳入的查詢與標頭參數，最後是 `extra_headers:` 和 `timeout:`。請求本文的鍵可以是 symbol 或字串；回應是以字串為鍵的 Hash，使用 API 自己的欄位名稱（`sent["id"]`），所以 API 參考逐欄位地描述了它們。`emails`、`inboxes` 和 `broadcasts` 有一個 `send` 方法，它會蓋掉這些物件上的 `Object#send`：要動態呼叫它們的方法，請用 `public_send`。

## 冪等與重試

八個傳送操作（`emails.send`、`emails.batch`、收到的郵件的回覆與轉寄、`inboxes.send`、`inboxes.drafts.send`、會話串的回覆與轉寄）一律會帶上 `Idempotency-Key`。沒有 `idempotency_key:` 時，每次呼叫都會自己產生一個，並在重試中沿用，所以逾時後的重試不會重複傳送；你自己的鍵還能讓另一個行程中的重複呼叫也保持安全。

值得重試的失敗預設會重試兩次：429、5xx、逾時、網路錯誤，以及同一個鍵的第一次請求仍在執行時回傳的 `409 concurrent_idempotent_requests`。只有重複執行也安全的請求才會重試：`GET`、`PUT`、`DELETE`，以及任何帶有 `Idempotency-Key` 的請求，每個傳送操作都是如此。用戶端依 `Retry-After` 的要求等待，要求超過一分鐘時會立即拋出；其餘情況從 0.5 秒到 8 秒採指數退避，並隨機減去最多四分之一。每個方法都接受 `timeout:` 和 `extra_headers:` 供該次呼叫使用，傳送類方法還接受 `idempotency_key:`；`max_retries:` 則在用戶端上設定。

## 錯誤

失敗的呼叫會拋出 `ValidationError`（400、422）、`AuthenticationError`（401，或沒有設定金鑰）、`PermissionDeniedError`（403）、`NotFoundError`（404）、`ConflictError`（409）、`RateLimitError`（429，`retry_after` 以秒為單位）、`APIError`（5xx）、`APIConnectionError`（沒有回應）或 `APITimeoutError`（這次嘗試逾時，是 `APIConnectionError` 的一種）。它們都在 `BillionSend` 模組中，並繼承 `BillionSend::Error`；其他任何狀態則直接以 `BillionSend::Error` 本身拋出，帶有 `status_code`、`name`（API 的錯誤名稱）、`message` 和 `request_id`；`request_id` 是回應的 `x-request-id`，也就是這個請求在控制台日誌頁面上的 id。

```ruby
begin
  puts client.emails.get(id)["subject"]
rescue BillionSend::NotFoundError
  # 沒有這封郵件
rescue BillionSend::Error => e
  warn "#{e.status_code} #{e.name}: #{e.message} (request #{e.request_id})"
end
```

## 列表

列表方法回傳一頁。每個游標式列表還有一個 `..._all` 方法（會話串搜尋是 `search_all`），回傳一個惰性的 `Enumerator`，會在迭代時取得後續的頁面，設定了 `before:` 時則向前取得：

```ruby
client.contacts.list_all(limit: 100).each do |contact|
  puts contact["email"]
end
```

## Agent 的收件匣

在[事件串流](/docs/zh-hant/inboxes)上等待新郵件，並在它所在的會話串中回覆：

```ruby
stream = client.inboxes.events.stream_inbox("support@acme.dev", types: "inbox.email.received")
begin
  stream.each do |event|
    next if event.is_a?(BillionSend::StreamGapEvent) # 事件可能有遺漏：重新讀取會話串

    data = event.data["data"]
    client.inboxes.threads.emails.reply(
      event.data["inbox_id"], data["thread_id"], data["email_id"],
      { text: "Thanks, we are on it." },
      idempotency_key: "reply/#{data["email_id"]}"
    )
  end
ensure
  stream.close
end
```

連線中斷時，事件串流會帶著 `Last-Event-ID` 重新連線，並補上錯過的事件；保留 `stream.last_event_id`，並用 `last_event_id:` 傳回去，就能在重新啟動後接續。從 24 小時前的位置恢復時，會收到一次 `StreamGapEvent`。`max_reconnects:`（預設連續失敗 5 次重新連線；`0` 表示第一次失敗就放棄）可調整重新連線的行為，每次嘗試前會等待一秒，或伺服器 `retry` 欄位所要求的時間。單一收件匣的事件串流在該收件匣被刪除或到期後結束；`client.inboxes.events.stream` 會追蹤金鑰能讀取的所有收件匣。

## 驗證 Webhook

`BillionSend.verify_webhook` 用端點的 `whsec_` 金鑰檢查一次 [Webhook](/docs/zh-hant/concepts/webhooks) 投遞的簽章和時間戳記，並回傳解析後的事件。傳入的請求本文必須與收到時完全一致；標頭名稱不分大小寫都能比對：

```ruby
# config.ru
require "billionsend"

SECRET = ENV.fetch("BILLIONSEND_WEBHOOK_SECRET")
NAMES = %w[webhook-id webhook-timestamp webhook-signature].freeze

app = lambda do |env|
  headers = NAMES.to_h { |name| [name, env["HTTP_#{name.upcase.tr("-", "_")}"]] }
  event = BillionSend.verify_webhook(env["rack.input"].read, headers, SECRET)
  warn event["type"]
  [204, {}, []]
rescue BillionSend::WebhookVerificationError
  [400, {}, ["bad signature"]]
end

run app
```

超過五分鐘的投遞會被拒絕，金鑰輪替期間，新舊兩個金鑰都能通過驗證。

## Agent 註冊

```ruby
signup = BillionSend::Client.new.agent.signup({ human_email: "owner@acme.dev", name: "Support agent" })
puts signup["inbox"]["email_address"]
```

這個呼叫不需要 API 金鑰；回應中帶有新的金鑰和收件匣。未認領的帳號可以做什麼，參閱 [Agent 註冊](/docs/zh-hant/agent-signup)。
