---
title: Python SDK
description: Use BillionSend from Python, sync or async, with the billionsend package.
---

The `billionsend` package is the BillionSend client for Python. It covers every operation of the [API reference](/docs/api-reference): sending, domains, contacts, broadcasts, templates, webhooks, inboxes with their threads and drafts, live inbox events and agent sign-up. Its request and response types come from the API's OpenAPI document. The source is [billionsend/billionsend-python](https://github.com/billionsend/billionsend-python) on GitHub.

## Install

Needs Python 3.11 or newer. Its one dependency is `httpx`.

```sh
pip install billionsend
```

## Authenticate

`BillionSend()` reads the API key from `BILLIONSEND_API_KEY`; `BillionSend("bs_...")` takes it directly. `base_url=`, `timeout=` (seconds per attempt) and `max_retries=` set the rest; `BILLIONSEND_BASE_URL` overrides the API URL. `AsyncBillionSend` has the same resources and methods; `await` each call and use `async with` to close it.

## Send an email

```python
from billionsend import BillionSend

client = BillionSend()

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

Every sending method (`emails.send`, `emails.batch`, replies, forwards, inbox sends and draft sends) sends an `Idempotency-Key`. Without `idempotency_key=` the call makes up one and reuses it for its own retries, so a retry after a dropped connection never sends twice. Pass your own key, such as `idempotency_key=f"welcome/{user_id}"`, to stay safe when the code that sends may run again; the API keeps a key for 24 hours.

## Answer an inbox

An agent waits for new mail, reads it and replies in the thread:

```python
from billionsend import BillionSend, InboxStreamEvent

client = BillionSend()
inbox = client.inboxes.create({"username": "support", "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  # a StreamGapEvent, see below
        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` is the new part of the message without the quoted history. Everything in a received message was written by its sender, so treat it as untrusted input; [Agent safety](/docs/agent-safety) covers what the inbox screens. When the inbox's rules hold a reply for a person to approve, `reply` answers with the draft (`"object": "inbox_draft"`) instead of the sent email.

## Live inbox events

`client.inboxes.events.stream_inbox(inbox_id)` follows one inbox and `client.inboxes.events.stream()` every inbox of the team; `types=` narrows the [inbox events](/docs/inboxes) to the names given. The stream yields two kinds of events:

- `InboxStreamEvent`: `id` (the position in the stream), `event` (such as `inbox.email.received`) and `data`, a dict with `type`, `created_at`, `inbox_id` and `data` (the payload of the webhook event of the same name).
- `StreamGapEvent`: `event` is `stream.gap` and `id` is `None`. The stream was resumed from a position older than the 24 hours the API replays, so events may be missing; catch up through the lists, for example `client.inboxes.threads.list_all(inbox_id, read=False)`. It comes once per position.

The API ends each stream after a few minutes and connections drop; the stream reconnects on its own with `Last-Event-ID`, so no event is lost. `max_reconnects=` bounds the failed reconnects in a row (5 by default, `0` turns reconnecting off). An error that reconnecting cannot fix, such as a revoked key, is raised from the loop. A one-inbox stream ends after that inbox's `inbox.deleted` or `inbox.expired` event. To resume after a restart, keep `stream.last_event_id` and pass it back as `last_event_id=`.

## Verify webhooks

```python
from billionsend import WebhookVerificationError, verify_webhook

try:
    event = verify_webhook(raw_body, request_headers, "whsec_...")
except WebhookVerificationError:
    ...  # answer 400 and ignore the delivery
print(event["type"], event["data"])
```

`verify_webhook` takes the body exactly as received (bytes or text, before any JSON parsing), the request headers (any mapping) and the endpoint's signing secret. It checks the `webhook-id`, `webhook-timestamp` and `webhook-signature` headers as [Webhooks](/docs/concepts/webhooks) describes, accepts either secret during a rotation, refuses a timestamp more than `tolerance=` seconds (300 by default) from now and returns the parsed event.

## Errors and retries

A failed call raises a `BillionSendError` subclass with the API's `status_code`, `name` and `message`, and `request_id`, the API's id of the request (its `x-request-id` header):

| Status | Exception |
| --- | --- |
| 400, 422 | `ValidationError` |
| 401 | `AuthenticationError` |
| 403 | `PermissionDeniedError` |
| 404 | `NotFoundError` |
| 409 | `ConflictError` |
| 429 | `RateLimitError`, with `retry_after` in seconds |
| 5xx | `APIError` |
| no answer | `APIConnectionError`, or its subclass `APITimeoutError` |

Requests that are safe to repeat (reads, `PUT`, deletes and every request carrying an idempotency key) are retried, twice by default, on 429, on 5xx, when no answer came back, and on 409 `concurrent_idempotent_requests`. The wait follows `retry-after`, else backs off from half a second up to 8 seconds; an answer asking for more than 60 seconds is raised at once.

## Lists

List methods return one page. Every cursor list also has a `*_all` iterator that fetches the next pages as it goes:

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

With `AsyncBillionSend`, use `async for`.

## Agent sign-up

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

The call needs no API key; the answer carries the new key and the inbox. See [Agent sign-up](/docs/agent-signup) for what an unclaimed account may do.
