---
title: Python SDK
description: 用 billionsend 套件在 Python 中傳送郵件、操作收件匣、驗證 Webhook，同步與非同步都支援，涵蓋全部 API 操作，內建重試與冪等鍵。
ai:
  exclude: true
---

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

## 安裝

需要 Python 3.11 或更新版本。它唯一的相依套件是 `httpx`。

```sh
pip install billionsend
```

## 身分驗證

`BillionSend()` 從 `BILLIONSEND_API_KEY` 讀取 API 金鑰；`BillionSend("bs_...")` 直接傳入金鑰。`base_url=`、`timeout=`（每次嘗試的秒數）和 `max_retries=` 設定其餘選項；`BILLIONSEND_BASE_URL` 可以覆寫 API 網址。`AsyncBillionSend` 有相同的資源和方法；每次呼叫都要 `await`，並用 `async with` 來關閉它。

## 傳送郵件

```python
from billionsend import BillionSend

client = BillionSend()

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

每個傳送類方法（`emails.send`、`emails.batch`、回覆、轉寄、收件匣傳送和草稿傳送）都會帶上 `Idempotency-Key`。沒有傳 `idempotency_key=` 時，呼叫會自己產生一個，並在自己的重試中沿用，所以連線中斷後的重試不會重複傳送。傳入你自己的鍵，例如 `idempotency_key=f"welcome/{user_id}"`，就能在傳送的程式碼可能再次執行時保持安全；API 會把一個鍵保留 24 小時。

## 回覆收件匣

Agent 等待新郵件，讀取它，並在會話串中回覆：

```python
from billionsend import BillionSend, InboxStreamEvent

client = BillionSend()
inbox = client.inboxes.create({"username": "research-agent", "kind": "agent"})

with client.inboxes.events.stream_inbox(inbox["id"], types="inbox.email.received") as stream:
    for event in stream:
        if not isinstance(event, InboxStreamEvent):
            continue  # 這是 StreamGapEvent，見下文
        thread_id = event.data["data"]["thread_id"]
        email_id = event.data["data"]["email_id"]
        email = client.inboxes.threads.emails.get(inbox["id"], thread_id, email_id)
        if email["direction"] != "inbound":
            continue
        question = email["extracted_text"] or email["text"] or ""
        client.inboxes.threads.emails.reply(
            inbox["id"], thread_id, email_id, {"text": f"You wrote: {question}"}
        )
```

`extracted_text` 是郵件中新寫的部分，不含引用的歷史內容。收到的郵件裡的一切都是寄件者寫的，所以請當成不可信的輸入；收件匣會篩選哪些內容，參閱 [Agent 安全](/docs/zh-hant/agent-safety)。收件匣的規則把回覆扣留給真人核准時，`reply` 會回傳草稿（`"object": "inbox_draft"`），而不是已傳送的郵件。

## 即時收件匣事件

`client.inboxes.events.stream_inbox(inbox_id)` 追蹤單一收件匣，`client.inboxes.events.stream()` 追蹤團隊的所有收件匣；`types=` 把[收件匣事件](/docs/zh-hant/inboxes)限定為所給的名稱。串流會產生兩種事件：

- `InboxStreamEvent`：`id`（在串流中的位置）、`event`（例如 `inbox.email.received`）和 `data`，後者是一個 dict，含有 `type`、`created_at`、`inbox_id` 和 `data`（同名 Webhook 事件的負載）。
- `StreamGapEvent`：`event` 為 `stream.gap`，`id` 為 `None`。串流是從比 API 重播的 24 小時更早的位置恢復的，所以事件可能有遺漏；請透過列表補上，例如 `client.inboxes.threads.list_all(inbox_id, read=False)`。每個位置只會出現一次。

API 在幾分鐘後會結束每個串流，連線也可能中斷；串流會自行以 `Last-Event-ID` 重新連線，所以不會遺失任何事件。`max_reconnects=` 限制連續失敗的重新連線次數（預設 5，`0` 會關閉重新連線）。重新連線也無法解決的錯誤，例如金鑰被撤銷，會從迴圈中拋出。單一收件匣的串流在該收件匣的 `inbox.deleted` 或 `inbox.expired` 事件之後結束。要在重新啟動後接續，請保留 `stream.last_event_id`，並用 `last_event_id=` 傳回去。

## 驗證 Webhook

```python
from billionsend import WebhookVerificationError, verify_webhook

try:
    event = verify_webhook(raw_body, request_headers, "whsec_...")
except WebhookVerificationError:
    ...  # 回應 400 並忽略這次投遞
print(event["type"], event["data"])
```

`verify_webhook` 接受收到時原樣的請求本文（bytes 或文字，在任何 JSON 解析之前）、請求標頭（任何 mapping）和端點的簽章金鑰。它依 [Webhook](/docs/zh-hant/concepts/webhooks) 所述檢查 `webhook-id`、`webhook-timestamp` 和 `webhook-signature` 標頭，在金鑰輪替期間兩個金鑰都接受，拒絕與現在相差超過 `tolerance=` 秒（預設 300）的時間戳記，並回傳解析後的事件。

## 錯誤與重試

失敗的呼叫會拋出一個 `BillionSendError` 的子類別，帶有 API 的 `status_code`、`name` 和 `message`，以及 `request_id`，也就是 API 給這個請求的 id（它的 `x-request-id` 標頭）：

| 狀態 | 例外 |
| --- | --- |
| 400、422 | `ValidationError` |
| 401 | `AuthenticationError` |
| 403 | `PermissionDeniedError` |
| 404 | `NotFoundError` |
| 409 | `ConflictError` |
| 429 | `RateLimitError`，`retry_after` 以秒為單位 |
| 5xx | `APIError` |
| 沒有回應 | `APIConnectionError`，或它的子類別 `APITimeoutError` |

重複執行也安全的請求（讀取、`PUT`、刪除，以及每個帶有冪等鍵的請求）會在 429、5xx、沒有回應和 409 `concurrent_idempotent_requests` 時重試，預設兩次。等待時間依 `retry-after`，否則從半秒開始退避，最長 8 秒；要求等待超過 60 秒的回應會立即拋出。

## 列表

列表方法回傳一頁。每個游標式列表還有一個 `*_all` 迭代器，會在迭代時取得後續的頁面：

```python
for contact in client.contacts.list_all(limit=100):
    print(contact["email"])
```

使用 `AsyncBillionSend` 時，請用 `async for`。

## Agent 註冊

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

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