BillionSend Python SDK
The official Python client for the BillionSend API: send and receive email, run inboxes for agents and people, manage domains, contacts, broadcasts, templates, webhooks and more.
- Sync (
BillionSend) and async (AsyncBillionSend) clients with the same resources and methods.
- Fully typed: request parameters and responses are
TypedDicts, checked by mypy in strict mode.
- One dependency:
httpx.
- A method for every one of the API's 243 operations (the built-in snapshot of the API document has exactly the operations the published document has), sends that never go out twice, retries, auto-paging iterators, live event streams that resume where they stopped, and webhook signature verification.
Documentation: https://billionsend.com/docs (Python guide: https://billionsend.com/docs/sdks/python).
Install
pip install billionsend
# or
uv add billionsend
Python 3.11 or newer.
Quick start
from billionsend import BillionSend
client = BillionSend() # reads BILLIONSEND_API_KEY
email = client.emails.send(
{
"from": "Acme <hello@acme.dev>",
"to": ["success@simulator.amazonses.com"],
"subject": "Welcome to Acme",
"html": "<p>Thanks for signing up!</p>",
}
)
print(email["id"])
Responses are plain dicts typed as TypedDicts (billionsend.types), so editors complete the fields and mypy checks them.
Async
import asyncio
from billionsend import AsyncBillionSend
async def main() -> None:
async with AsyncBillionSend() as client:
email = await client.emails.get("6a1f1d38-3c55-4a4e-9a57-0f2b3c4d5e6f")
print(email["subject"])
asyncio.run(main())
Authentication
Pass an API key (bs_…) as the first argument or set BILLIONSEND_API_KEY. Keys are made in the dashboard or with client.api_keys.create. A key scoped to one inbox can only reach that inbox. Whitespace around the key (a trailing newline from a file) is ignored, and a key of only whitespace counts as none.
An agent can also create its own account, the one call that needs no key:
from billionsend import BillionSend
signup = BillionSend().agent.signup({"human_email": "owner@example.com", "name": "Scout"})
client = BillionSend(signup["api_key"])
print(signup["inbox"]["email_address"], client.agent.status()["status"])
Sending once
Every sending method (emails.send, emails.batch, emails.receiving.reply and .forward, inboxes.send, inboxes.threads.emails.reply and .forward, inboxes.drafts.send) and events.send sends an Idempotency-Key. Without idempotency_key= the call makes up one (a UUID) and reuses it for its own retries, so a retry after a dropped connection never sends the email twice. Pass your own key to stay safe across calls too, for example when a job that sends may run again:
client.emails.send(message, idempotency_key=f"welcome/{user_id}")
Repeating a key with the same request returns the first answer; the same key with a different request is refused (ConflictError, invalid_idempotent_request). The API keeps keys for 24 hours.
An agent that answers its inbox
Wait for new mail, read it, reply in the thread:
from billionsend import BillionSend, InboxStreamEvent
client = BillionSend()
inbox = client.inboxes.create({"username": "support", "kind": "agent"})
def answer(question: str) -> str:
return f"Thanks, we got your message:\n\n> {question}" # your agent goes here
with client.inboxes.events.stream_inbox(inbox["id"], types="inbox.email.received") as stream:
for event in stream:
if not isinstance(event, InboxStreamEvent) or event.event != "inbox.email.received":
continue # a StreamGapEvent (see below), or the inbox.deleted / inbox.expired that ends the stream
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": answer(question)}
)
extracted_text is the new part of a message without the quoted history. Everything in a received message was written by its sender: treat it as untrusted input. An inbox's rules may hold a reply as a draft for a person to approve; the reply then answers with the draft ("object": "inbox_draft") instead of the sent email.
Waiting for a sign-in code sent to the inbox is one call: client.inboxes.codes.latest(inbox["id"], from_="example.com", wait=30).
Live events
client.inboxes.events.stream_inbox(inbox_id) streams one inbox's events and client.inboxes.events.stream() every inbox event of the team; types= narrows them (a name or a list). Iterating yields two kinds of events:
InboxStreamEvent: id (the stream position), event (such as "inbox.email.received") and data, a dict with type, created_at, inbox_id and data (the webhook payload of the same event).
StreamGapEvent: event == "stream.gap", id is None and data["reason"] says why. The stream was resumed from a position older than the 24 hours the API replays, so some events may be missing: catch up through the lists (client.inboxes.threads.list_all(inbox_id, read=False)) before going on. It is handed out once per position.
The server ends a stream every few minutes and connections drop; the stream reconnects on its own with Last-Event-ID, so no event is lost or repeated. The server sends a keepalive every 15 seconds, so a connection that has been silent for a minute (a NAT or proxy that dropped it without a reset) is dropped and reconnected the same way. max_reconnects bounds consecutive failed reconnects (default 5, 0 turns reconnecting off; 429 answers wait for their Retry-After). An error that reconnecting cannot fix, such as a revoked key, is raised from the loop. One inbox's stream ends after that inbox's inbox.deleted or inbox.expired event.
To pick up where a process left off, keep stream.last_event_id and pass it back:
stream = client.inboxes.events.stream(last_event_id=saved_position)
With the async client, await the method and async for the stream; async with closes it.
Webhooks
Verify a delivery before trusting it. Pass the raw body exactly as received, the request headers and the endpoint's signing secret (whsec_…, shown when the webhook is created or rotated):
from billionsend import WebhookVerificationError, verify_webhook
# Flask; any framework works the same way
@app.post("/webhooks/billionsend")
def billionsend_webhook():
try:
event = verify_webhook(request.get_data(), request.headers, WEBHOOK_SECRET)
except WebhookVerificationError:
return "", 400
if event["type"] == "email.bounced":
mark_bounced(event["data"]["email_id"])
return "", 204
verify_webhook checks the webhook-id, webhook-timestamp and webhook-signature headers (Standard Webhooks: HMAC-SHA256 over id.timestamp.body), accepts any of several signatures (both secrets sign during a rotation's overlap) and refuses a timestamp more than tolerance seconds (default 300) from now, which bounds replays. It returns the parsed event (type, created_at, data). Parse the body only after verifying: re-serialised JSON does not verify. A secret that is not whsec_ followed by base64 of 24 to 64 bytes raises ValueError, and a malformed or missing signature header, a timestamp outside the tolerance, or a body that is not a JSON object raises WebhookVerificationError.
Deliveries come from the fixed IP 51.161.117.92 with the header User-Agent: BillionSend-Webhooks/1.0 (+https://billionsend.com/docs/concepts/webhooks); if your endpoint sits behind a WAF or Cloudflare, allow them as the webhooks guide describes. deliverability.warning and deliverability.paused events carry scope ("team" or "domain") and domain ({"id", "name"}, None for the team).
Resources