---
title: Python SDK
description: 用 billionsend 包在 Python 里发送邮件、使用收件箱、验证 Webhook，同步与异步都支持，覆盖全部 API 操作，内置重试与幂等键。
ai:
  exclude: true
---

`billionsend` 是 BillionSend 面向 Python 的客户端。它覆盖 [API 参考](/docs/zh-hans/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-hans/agent-safety)说明了收件箱会筛查什么。当收件箱的规则把一次回复扣留下来等人批准时，`reply` 返回的是草稿（`"object": "inbox_draft"`），而不是已发送的邮件。

## 实时收件箱事件

`client.inboxes.events.stream_inbox(inbox_id)` 跟随一个收件箱，`client.inboxes.events.stream()` 跟随团队的所有收件箱；`types=` 把[收件箱事件](/docs/zh-hans/inboxes)限定为指定的名称。事件流会产出两种事件：

- `InboxStreamEvent`：`id`（在事件流中的位置）、`event`（如 `inbox.email.received`）和 `data`，后者是一个字典，包含 `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` 接收收到时原样的请求体（字节或文本，在任何 JSON 解析之前）、请求头（任何映射）和端点的签名密钥。它按 [Webhook](/docs/zh-hans/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-hans/agent-signup)。
