billionsend 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- billionsend-0.1.0/.gitignore +10 -0
- billionsend-0.1.0/CHANGELOG.md +14 -0
- billionsend-0.1.0/LICENSE +21 -0
- billionsend-0.1.0/PKG-INFO +306 -0
- billionsend-0.1.0/README.md +279 -0
- billionsend-0.1.0/pyproject.toml +76 -0
- billionsend-0.1.0/src/billionsend/__init__.py +63 -0
- billionsend-0.1.0/src/billionsend/_base_client.py +562 -0
- billionsend-0.1.0/src/billionsend/_client.py +212 -0
- billionsend-0.1.0/src/billionsend/_exceptions.py +152 -0
- billionsend-0.1.0/src/billionsend/_pagination.py +46 -0
- billionsend-0.1.0/src/billionsend/_streaming.py +461 -0
- billionsend-0.1.0/src/billionsend/_version.py +1 -0
- billionsend-0.1.0/src/billionsend/_webhooks.py +127 -0
- billionsend-0.1.0/src/billionsend/py.typed +0 -0
- billionsend-0.1.0/src/billionsend/resources/__init__.py +4 -0
- billionsend-0.1.0/src/billionsend/resources/_async.py +4501 -0
- billionsend-0.1.0/src/billionsend/resources/_sync.py +4499 -0
- billionsend-0.1.0/src/billionsend/types.py +2737 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 (2026-11-17)
|
|
4
|
+
|
|
5
|
+
First release of the BillionSend Python SDK.
|
|
6
|
+
|
|
7
|
+
- `BillionSend` and `AsyncBillionSend` clients covering every operation of the BillionSend API (136), named after each operation's `operationId` and grouped into resources: emails (with receiving, attachments and their extracted text), domains, API keys, contacts, audiences, contact properties, segments, topics, broadcasts, templates, webhooks, suppressions, unsubscribes, verifications, usage, deliverability, inboxes (agent and safety settings, labels, threads, quarantine, codes, drafts, event streams) and agent signup.
|
|
8
|
+
- Request parameters and responses typed as `TypedDict`s generated from the OpenAPI document; mypy strict clean, `py.typed` included.
|
|
9
|
+
- Errors raised as `BillionSendError` subclasses carrying `status_code`, `name`, `message` and `request_id` (the API's `x-request-id`).
|
|
10
|
+
- Sending methods always send an `Idempotency-Key`: the caller's, or a UUID made up for the call and shared by its retries.
|
|
11
|
+
- Retries for requests safe to repeat (GET, PUT, DELETE and keyed requests) on 429, 5xx, failures without an answer and 409 `concurrent_idempotent_requests`, honouring `Retry-After` up to 60 seconds, else exponential backoff with jitter.
|
|
12
|
+
- Server-sent event streams (sync and async iterators) yielding typed `InboxStreamEvent` and `StreamGapEvent` objects, resuming with `Last-Event-ID` after the server closes them or the connection drops.
|
|
13
|
+
- `*_all` iterators that page through every cursor list.
|
|
14
|
+
- `verify_webhook` checks a webhook delivery's signature and timestamp and returns the parsed event.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 BillionSend
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: billionsend
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK for the BillionSend email API: sending, receiving, inboxes for agents, contacts, broadcasts and more.
|
|
5
|
+
Project-URL: Homepage, https://billionsend.com
|
|
6
|
+
Project-URL: Documentation, https://billionsend.com/docs/sdks/python
|
|
7
|
+
Project-URL: Repository, https://github.com/billionsend/billionsend-python
|
|
8
|
+
Project-URL: Changelog, https://github.com/billionsend/billionsend-python/blob/main/CHANGELOG.md
|
|
9
|
+
Author: BillionSend
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: api,billionsend,email,inbox,sdk,smtp
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Topic :: Communications :: Email
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.11
|
|
25
|
+
Requires-Dist: httpx<1,>=0.27
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# BillionSend Python SDK
|
|
29
|
+
|
|
30
|
+
The official Python client for the [BillionSend](https://billionsend.com) API: send and receive email, run inboxes for agents and people, manage domains, contacts, broadcasts, templates, webhooks and more.
|
|
31
|
+
|
|
32
|
+
- Sync (`BillionSend`) and async (`AsyncBillionSend`) clients with the same resources and methods.
|
|
33
|
+
- Fully typed: request parameters and responses are `TypedDict`s, checked by mypy in strict mode.
|
|
34
|
+
- One dependency: [`httpx`](https://www.python-httpx.org/).
|
|
35
|
+
- Every operation of the API, sends that never go out twice, retries, auto-paging iterators, live event streams that resume where they stopped, and webhook signature verification.
|
|
36
|
+
|
|
37
|
+
Documentation: https://billionsend.com/docs (Python guide: https://billionsend.com/docs/sdks/python).
|
|
38
|
+
|
|
39
|
+
## Install
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pip install billionsend
|
|
43
|
+
# or
|
|
44
|
+
uv add billionsend
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Python 3.11 or newer.
|
|
48
|
+
|
|
49
|
+
## Quick start
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
from billionsend import BillionSend
|
|
53
|
+
|
|
54
|
+
client = BillionSend() # reads BILLIONSEND_API_KEY
|
|
55
|
+
|
|
56
|
+
email = client.emails.send(
|
|
57
|
+
{
|
|
58
|
+
"from": "Acme <hello@acme.dev>",
|
|
59
|
+
"to": ["ada@example.com"],
|
|
60
|
+
"subject": "Welcome to Acme",
|
|
61
|
+
"html": "<p>Thanks for signing up!</p>",
|
|
62
|
+
}
|
|
63
|
+
)
|
|
64
|
+
print(email["id"])
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Responses are plain `dict`s typed as `TypedDict`s (`billionsend.types`), so editors complete the fields and mypy checks them.
|
|
68
|
+
|
|
69
|
+
### Async
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
import asyncio
|
|
73
|
+
|
|
74
|
+
from billionsend import AsyncBillionSend
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
async def main() -> None:
|
|
78
|
+
async with AsyncBillionSend() as client:
|
|
79
|
+
email = await client.emails.get("6a1f1d38-3c55-4a4e-9a57-0f2b3c4d5e6f")
|
|
80
|
+
print(email["subject"])
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
asyncio.run(main())
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Authentication
|
|
87
|
+
|
|
88
|
+
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.
|
|
89
|
+
|
|
90
|
+
An agent can also create its own account, the one call that needs no key:
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
from billionsend import BillionSend
|
|
94
|
+
|
|
95
|
+
signup = BillionSend().agent.signup({"human_email": "owner@example.com", "name": "Scout"})
|
|
96
|
+
client = BillionSend(signup["api_key"])
|
|
97
|
+
print(signup["inbox"]["email_address"], client.agent.status()["status"])
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## Sending once
|
|
101
|
+
|
|
102
|
+
Every sending method (`emails.send`, `emails.batch`, `emails.receiving.reply` and `.forward`, `inboxes.send`, `inboxes.threads.emails.reply` and `.forward`, `inboxes.drafts.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:
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
client.emails.send(message, idempotency_key=f"welcome/{user_id}")
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
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.
|
|
109
|
+
|
|
110
|
+
## An agent that answers its inbox
|
|
111
|
+
|
|
112
|
+
Wait for new mail, read it, reply in the thread:
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
from billionsend import BillionSend, InboxStreamEvent
|
|
116
|
+
|
|
117
|
+
client = BillionSend()
|
|
118
|
+
inbox = client.inboxes.create({"username": "support", "kind": "agent"})
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def answer(question: str) -> str:
|
|
122
|
+
return f"Thanks, we got your message:\n\n> {question}" # your agent goes here
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
with client.inboxes.events.stream_inbox(inbox["id"], types="inbox.email.received") as stream:
|
|
126
|
+
for event in stream:
|
|
127
|
+
if not isinstance(event, InboxStreamEvent):
|
|
128
|
+
continue # a StreamGapEvent: see below
|
|
129
|
+
thread_id = event.data["data"]["thread_id"]
|
|
130
|
+
email_id = event.data["data"]["email_id"]
|
|
131
|
+
email = client.inboxes.threads.emails.get(inbox["id"], thread_id, email_id)
|
|
132
|
+
if email["direction"] != "inbound":
|
|
133
|
+
continue
|
|
134
|
+
question = email["extracted_text"] or email["text"] or ""
|
|
135
|
+
client.inboxes.threads.emails.reply(
|
|
136
|
+
inbox["id"], thread_id, email_id, {"text": answer(question)}
|
|
137
|
+
)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
`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.
|
|
141
|
+
|
|
142
|
+
Waiting for a sign-in code sent to the inbox is one call: `client.inboxes.codes.latest(inbox["id"], from_="example.com", wait=30)`.
|
|
143
|
+
|
|
144
|
+
## Live events
|
|
145
|
+
|
|
146
|
+
`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:
|
|
147
|
+
|
|
148
|
+
- `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).
|
|
149
|
+
- `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.
|
|
150
|
+
|
|
151
|
+
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. `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.
|
|
152
|
+
|
|
153
|
+
To pick up where a process left off, keep `stream.last_event_id` and pass it back:
|
|
154
|
+
|
|
155
|
+
```python
|
|
156
|
+
stream = client.inboxes.events.stream(last_event_id=saved_position)
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
With the async client, `await` the method and `async for` the stream; `async with` closes it.
|
|
160
|
+
|
|
161
|
+
## Webhooks
|
|
162
|
+
|
|
163
|
+
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):
|
|
164
|
+
|
|
165
|
+
```python
|
|
166
|
+
from billionsend import WebhookVerificationError, verify_webhook
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# Flask; any framework works the same way
|
|
170
|
+
@app.post("/webhooks/billionsend")
|
|
171
|
+
def billionsend_webhook():
|
|
172
|
+
try:
|
|
173
|
+
event = verify_webhook(request.get_data(), request.headers, WEBHOOK_SECRET)
|
|
174
|
+
except WebhookVerificationError:
|
|
175
|
+
return "", 400
|
|
176
|
+
if event["type"] == "email.bounced":
|
|
177
|
+
mark_bounced(event["data"]["email_id"])
|
|
178
|
+
return "", 204
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
`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 a `whsec_` secret raises `ValueError`.
|
|
182
|
+
|
|
183
|
+
## Resources
|
|
184
|
+
|
|
185
|
+
| Attribute | Covers |
|
|
186
|
+
| --- | --- |
|
|
187
|
+
| `emails` | send, batch, list, get, update, cancel, delete, insights, metrics |
|
|
188
|
+
| `emails.receiving` (`.attachments`) | received mail: list, get, delete, reply, forward; attachments |
|
|
189
|
+
| `domains` | create, list, get, update, delete, verify |
|
|
190
|
+
| `api_keys` | create, list, delete |
|
|
191
|
+
| `contacts` (`.topics`, `.segments`, `.batch`) | create, list, get, update, delete, preferences_link; `batch.create`, `batch.get`, `batch.remove` |
|
|
192
|
+
| `audiences.contacts` | contacts addressed through an audience |
|
|
193
|
+
| `contact_properties`, `segments` (`.contacts`), `topics` | contact data and grouping |
|
|
194
|
+
| `broadcasts` | create, list, get, update, delete, send, duplicate, cancel |
|
|
195
|
+
| `templates` | create, list, get, update, delete, publish, duplicate |
|
|
196
|
+
| `webhooks` | create, list, get, update, delete, rotate |
|
|
197
|
+
| `suppressions` (`.batch`), `unsubscribes` | suppression list (`batch.add`, `batch.remove`) and opt-outs |
|
|
198
|
+
| `verifications` | availability, estimate, create, list, get |
|
|
199
|
+
| `usage`, `deliverability` | account usage and sending health |
|
|
200
|
+
| `inboxes` (`.events`) | create, list, get, update, delete, send; `events.stream`, `events.stream_inbox` |
|
|
201
|
+
| `inboxes.agent`, `.safety`, `.labels`, `.codes`, `.quarantine`, `.drafts` | inbox settings, labels, verification codes, held mail, drafts |
|
|
202
|
+
| `inboxes.threads` (`.labels`, `.emails`) | list, search, get, update, delete; thread labels; messages, reply and forward |
|
|
203
|
+
| `agent` | signup, status, claim_email |
|
|
204
|
+
|
|
205
|
+
Each method is named after its operation's `operationId` in the API document: `emails.receiving.attachments.list` is `client.emails.receiving.attachments.list`, with camelCase written in snake_case (`agent.claimEmail` is `client.agent.claim_email`).
|
|
206
|
+
|
|
207
|
+
Path parameters are positional (`client.domains.get(domain_id)`), the request body is a `dict` (`client.domains.create({"name": "acme.dev"})`) and query parameters are keyword arguments (`client.emails.list(limit=50)`). A parameter named after a Python keyword takes a trailing underscore (`from_=`). Every method also takes `extra_headers=` and `timeout=`.
|
|
208
|
+
|
|
209
|
+
## Pagination
|
|
210
|
+
|
|
211
|
+
List methods return one page (`{"object": "list", "data": [...], "has_more": ...}`). Every cursor list also has a `*_all` iterator (`search_all` for thread search) that fetches the following pages as you go:
|
|
212
|
+
|
|
213
|
+
```python
|
|
214
|
+
for contact in client.contacts.list_all(limit=100):
|
|
215
|
+
print(contact["email"])
|
|
216
|
+
|
|
217
|
+
# async
|
|
218
|
+
async for domain in async_client.domains.list_all():
|
|
219
|
+
print(domain["name"])
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
An iterator walks in the list's own order from `after` (or the first page); start it with `before` to walk the other way. It raises the same errors as the methods.
|
|
223
|
+
|
|
224
|
+
## Errors
|
|
225
|
+
|
|
226
|
+
Every error is a `BillionSendError` with the API's error shape, `status_code`, `name` and `message`, plus `request_id`, the API's id of the request (its `x-request-id` header; quote it when asking for support).
|
|
227
|
+
|
|
228
|
+
```python
|
|
229
|
+
from billionsend import BillionSend, BillionSendError, NotFoundError, RateLimitError
|
|
230
|
+
|
|
231
|
+
client = BillionSend()
|
|
232
|
+
try:
|
|
233
|
+
client.domains.get("6a1f1d38-3c55-4a4e-9a57-0f2b3c4d5e6f")
|
|
234
|
+
except NotFoundError:
|
|
235
|
+
print("no such domain")
|
|
236
|
+
except RateLimitError as err:
|
|
237
|
+
print("retry in", err.retry_after)
|
|
238
|
+
except BillionSendError as err:
|
|
239
|
+
print(err.status_code, err.name, err.message, err.request_id)
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
| Status | Exception |
|
|
243
|
+
| --- | --- |
|
|
244
|
+
| 400, 422 | `ValidationError` |
|
|
245
|
+
| 401 | `AuthenticationError` |
|
|
246
|
+
| 403 | `PermissionDeniedError` |
|
|
247
|
+
| 404 | `NotFoundError` |
|
|
248
|
+
| 409 | `ConflictError` |
|
|
249
|
+
| 429 | `RateLimitError` (`retry_after` in seconds) |
|
|
250
|
+
| 5xx | `APIError` |
|
|
251
|
+
| no answer | `APIConnectionError`, and `APITimeoutError` (a subclass) for timeouts; `status_code` and `request_id` are `None` |
|
|
252
|
+
|
|
253
|
+
An answer that is not JSON keeps the same shape, with `name` set to `"application_error"`. `WebhookVerificationError` (`name` `"webhook_verification_error"`) is a `BillionSendError` too.
|
|
254
|
+
|
|
255
|
+
## Retries
|
|
256
|
+
|
|
257
|
+
A request is retried when repeating it is safe: GET, PUT and DELETE, and any request carrying an idempotency key (every send does). It is retried on 429, on 5xx, when no answer came back (connection failure, timeout), and, for a keyed request, on 409 `concurrent_idempotent_requests` (a retry that caught the first attempt still running). The wait is the answer's `Retry-After` when there is one, otherwise exponential backoff with jitter (0.5 s, 1 s, 2 s… up to 8 s). An answer asking to wait more than 60 seconds, such as a used-up daily quota, is raised at once. `max_retries` (default 2) bounds the retries of one call; `0` turns them off.
|
|
258
|
+
|
|
259
|
+
## Configuration
|
|
260
|
+
|
|
261
|
+
| Argument | Environment | Default |
|
|
262
|
+
| --- | --- | --- |
|
|
263
|
+
| `api_key` | `BILLIONSEND_API_KEY` | none (only `agent.signup` works without one) |
|
|
264
|
+
| `base_url` | `BILLIONSEND_BASE_URL` | `https://api.billionsend.com` |
|
|
265
|
+
| `timeout` | | `60` seconds per attempt, or an `httpx.Timeout` |
|
|
266
|
+
| `max_retries` | | `2` |
|
|
267
|
+
| `default_headers` | | none |
|
|
268
|
+
| `http_client` | | an `httpx.Client` / `httpx.AsyncClient` of your own (proxies, transports); the SDK does not close it |
|
|
269
|
+
|
|
270
|
+
Close the client with `client.close()` (`await client.close()`) or use it as a context manager.
|
|
271
|
+
|
|
272
|
+
## Development
|
|
273
|
+
|
|
274
|
+
```bash
|
|
275
|
+
uv sync
|
|
276
|
+
uv run ruff check . && uv run ruff format --check .
|
|
277
|
+
uv run mypy
|
|
278
|
+
uv run pytest
|
|
279
|
+
uv build
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
The SDK is built from a snapshot of the API's OpenAPI document, `openapi/api.openapi.json`. The snapshot is the contract: `scripts/generate.py` writes `src/billionsend/types.py` and the resource modules from it (method names from each `operationId`, idempotency keys where an operation declares the `Idempotency-Key` header, iterators for cursor lists), and the tests validate every request the SDK sends and every response it receives against it through a contract mock (`tests/contract.py`). A coverage test fails when an operation of the snapshot has no SDK method, or when the SDK calls something the snapshot does not declare.
|
|
283
|
+
|
|
284
|
+
When the API changes:
|
|
285
|
+
|
|
286
|
+
```bash
|
|
287
|
+
uv run python scripts/sync_openapi.py # or: --from path/to/api.openapi.json
|
|
288
|
+
uv run python scripts/generate.py
|
|
289
|
+
uv run pytest
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
Whatever fails is what the SDK has to follow. CI runs `scripts/generate.py --check` so the generated code never drifts from the snapshot.
|
|
293
|
+
|
|
294
|
+
## Releasing
|
|
295
|
+
|
|
296
|
+
Publishing is manual; nothing is published on push.
|
|
297
|
+
|
|
298
|
+
1. On PyPI, the owner of the `billionsend` project adds a Trusted Publisher (for the first version, a "pending publisher" under Account → Publishing): owner `billionsend`, repository `billionsend-python`, workflow `release.yml`, environment `pypi`.
|
|
299
|
+
2. Set `version` in `pyproject.toml`, turn the changelog's `Unreleased` heading into that version, commit, then tag and push: `git tag v0.1.0 && git push origin main v0.1.0`.
|
|
300
|
+
3. Actions → `release` → Run workflow, on the version tag. The workflow refuses a branch or a tag that differs from `pyproject.toml`, runs every check, builds the sdist and wheel, and uploads them with PyPI Trusted Publishing (no token stored).
|
|
301
|
+
|
|
302
|
+
Without Trusted Publishing, the same release from a clean checkout of the tag is `uv build && uv publish` with an API token scoped to the `billionsend` project in `UV_PUBLISH_TOKEN`.
|
|
303
|
+
|
|
304
|
+
## License
|
|
305
|
+
|
|
306
|
+
MIT
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
# BillionSend Python SDK
|
|
2
|
+
|
|
3
|
+
The official Python client for the [BillionSend](https://billionsend.com) API: send and receive email, run inboxes for agents and people, manage domains, contacts, broadcasts, templates, webhooks and more.
|
|
4
|
+
|
|
5
|
+
- Sync (`BillionSend`) and async (`AsyncBillionSend`) clients with the same resources and methods.
|
|
6
|
+
- Fully typed: request parameters and responses are `TypedDict`s, checked by mypy in strict mode.
|
|
7
|
+
- One dependency: [`httpx`](https://www.python-httpx.org/).
|
|
8
|
+
- Every operation of the API, sends that never go out twice, retries, auto-paging iterators, live event streams that resume where they stopped, and webhook signature verification.
|
|
9
|
+
|
|
10
|
+
Documentation: https://billionsend.com/docs (Python guide: https://billionsend.com/docs/sdks/python).
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pip install billionsend
|
|
16
|
+
# or
|
|
17
|
+
uv add billionsend
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Python 3.11 or newer.
|
|
21
|
+
|
|
22
|
+
## Quick start
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from billionsend import BillionSend
|
|
26
|
+
|
|
27
|
+
client = BillionSend() # reads BILLIONSEND_API_KEY
|
|
28
|
+
|
|
29
|
+
email = client.emails.send(
|
|
30
|
+
{
|
|
31
|
+
"from": "Acme <hello@acme.dev>",
|
|
32
|
+
"to": ["ada@example.com"],
|
|
33
|
+
"subject": "Welcome to Acme",
|
|
34
|
+
"html": "<p>Thanks for signing up!</p>",
|
|
35
|
+
}
|
|
36
|
+
)
|
|
37
|
+
print(email["id"])
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Responses are plain `dict`s typed as `TypedDict`s (`billionsend.types`), so editors complete the fields and mypy checks them.
|
|
41
|
+
|
|
42
|
+
### Async
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import asyncio
|
|
46
|
+
|
|
47
|
+
from billionsend import AsyncBillionSend
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
async def main() -> None:
|
|
51
|
+
async with AsyncBillionSend() as client:
|
|
52
|
+
email = await client.emails.get("6a1f1d38-3c55-4a4e-9a57-0f2b3c4d5e6f")
|
|
53
|
+
print(email["subject"])
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
asyncio.run(main())
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Authentication
|
|
60
|
+
|
|
61
|
+
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.
|
|
62
|
+
|
|
63
|
+
An agent can also create its own account, the one call that needs no key:
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from billionsend import BillionSend
|
|
67
|
+
|
|
68
|
+
signup = BillionSend().agent.signup({"human_email": "owner@example.com", "name": "Scout"})
|
|
69
|
+
client = BillionSend(signup["api_key"])
|
|
70
|
+
print(signup["inbox"]["email_address"], client.agent.status()["status"])
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Sending once
|
|
74
|
+
|
|
75
|
+
Every sending method (`emails.send`, `emails.batch`, `emails.receiving.reply` and `.forward`, `inboxes.send`, `inboxes.threads.emails.reply` and `.forward`, `inboxes.drafts.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:
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
client.emails.send(message, idempotency_key=f"welcome/{user_id}")
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
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.
|
|
82
|
+
|
|
83
|
+
## An agent that answers its inbox
|
|
84
|
+
|
|
85
|
+
Wait for new mail, read it, reply in the thread:
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from billionsend import BillionSend, InboxStreamEvent
|
|
89
|
+
|
|
90
|
+
client = BillionSend()
|
|
91
|
+
inbox = client.inboxes.create({"username": "support", "kind": "agent"})
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def answer(question: str) -> str:
|
|
95
|
+
return f"Thanks, we got your message:\n\n> {question}" # your agent goes here
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
with client.inboxes.events.stream_inbox(inbox["id"], types="inbox.email.received") as stream:
|
|
99
|
+
for event in stream:
|
|
100
|
+
if not isinstance(event, InboxStreamEvent):
|
|
101
|
+
continue # a StreamGapEvent: see below
|
|
102
|
+
thread_id = event.data["data"]["thread_id"]
|
|
103
|
+
email_id = event.data["data"]["email_id"]
|
|
104
|
+
email = client.inboxes.threads.emails.get(inbox["id"], thread_id, email_id)
|
|
105
|
+
if email["direction"] != "inbound":
|
|
106
|
+
continue
|
|
107
|
+
question = email["extracted_text"] or email["text"] or ""
|
|
108
|
+
client.inboxes.threads.emails.reply(
|
|
109
|
+
inbox["id"], thread_id, email_id, {"text": answer(question)}
|
|
110
|
+
)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`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.
|
|
114
|
+
|
|
115
|
+
Waiting for a sign-in code sent to the inbox is one call: `client.inboxes.codes.latest(inbox["id"], from_="example.com", wait=30)`.
|
|
116
|
+
|
|
117
|
+
## Live events
|
|
118
|
+
|
|
119
|
+
`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:
|
|
120
|
+
|
|
121
|
+
- `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).
|
|
122
|
+
- `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.
|
|
123
|
+
|
|
124
|
+
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. `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.
|
|
125
|
+
|
|
126
|
+
To pick up where a process left off, keep `stream.last_event_id` and pass it back:
|
|
127
|
+
|
|
128
|
+
```python
|
|
129
|
+
stream = client.inboxes.events.stream(last_event_id=saved_position)
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
With the async client, `await` the method and `async for` the stream; `async with` closes it.
|
|
133
|
+
|
|
134
|
+
## Webhooks
|
|
135
|
+
|
|
136
|
+
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):
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
from billionsend import WebhookVerificationError, verify_webhook
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# Flask; any framework works the same way
|
|
143
|
+
@app.post("/webhooks/billionsend")
|
|
144
|
+
def billionsend_webhook():
|
|
145
|
+
try:
|
|
146
|
+
event = verify_webhook(request.get_data(), request.headers, WEBHOOK_SECRET)
|
|
147
|
+
except WebhookVerificationError:
|
|
148
|
+
return "", 400
|
|
149
|
+
if event["type"] == "email.bounced":
|
|
150
|
+
mark_bounced(event["data"]["email_id"])
|
|
151
|
+
return "", 204
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
`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 a `whsec_` secret raises `ValueError`.
|
|
155
|
+
|
|
156
|
+
## Resources
|
|
157
|
+
|
|
158
|
+
| Attribute | Covers |
|
|
159
|
+
| --- | --- |
|
|
160
|
+
| `emails` | send, batch, list, get, update, cancel, delete, insights, metrics |
|
|
161
|
+
| `emails.receiving` (`.attachments`) | received mail: list, get, delete, reply, forward; attachments |
|
|
162
|
+
| `domains` | create, list, get, update, delete, verify |
|
|
163
|
+
| `api_keys` | create, list, delete |
|
|
164
|
+
| `contacts` (`.topics`, `.segments`, `.batch`) | create, list, get, update, delete, preferences_link; `batch.create`, `batch.get`, `batch.remove` |
|
|
165
|
+
| `audiences.contacts` | contacts addressed through an audience |
|
|
166
|
+
| `contact_properties`, `segments` (`.contacts`), `topics` | contact data and grouping |
|
|
167
|
+
| `broadcasts` | create, list, get, update, delete, send, duplicate, cancel |
|
|
168
|
+
| `templates` | create, list, get, update, delete, publish, duplicate |
|
|
169
|
+
| `webhooks` | create, list, get, update, delete, rotate |
|
|
170
|
+
| `suppressions` (`.batch`), `unsubscribes` | suppression list (`batch.add`, `batch.remove`) and opt-outs |
|
|
171
|
+
| `verifications` | availability, estimate, create, list, get |
|
|
172
|
+
| `usage`, `deliverability` | account usage and sending health |
|
|
173
|
+
| `inboxes` (`.events`) | create, list, get, update, delete, send; `events.stream`, `events.stream_inbox` |
|
|
174
|
+
| `inboxes.agent`, `.safety`, `.labels`, `.codes`, `.quarantine`, `.drafts` | inbox settings, labels, verification codes, held mail, drafts |
|
|
175
|
+
| `inboxes.threads` (`.labels`, `.emails`) | list, search, get, update, delete; thread labels; messages, reply and forward |
|
|
176
|
+
| `agent` | signup, status, claim_email |
|
|
177
|
+
|
|
178
|
+
Each method is named after its operation's `operationId` in the API document: `emails.receiving.attachments.list` is `client.emails.receiving.attachments.list`, with camelCase written in snake_case (`agent.claimEmail` is `client.agent.claim_email`).
|
|
179
|
+
|
|
180
|
+
Path parameters are positional (`client.domains.get(domain_id)`), the request body is a `dict` (`client.domains.create({"name": "acme.dev"})`) and query parameters are keyword arguments (`client.emails.list(limit=50)`). A parameter named after a Python keyword takes a trailing underscore (`from_=`). Every method also takes `extra_headers=` and `timeout=`.
|
|
181
|
+
|
|
182
|
+
## Pagination
|
|
183
|
+
|
|
184
|
+
List methods return one page (`{"object": "list", "data": [...], "has_more": ...}`). Every cursor list also has a `*_all` iterator (`search_all` for thread search) that fetches the following pages as you go:
|
|
185
|
+
|
|
186
|
+
```python
|
|
187
|
+
for contact in client.contacts.list_all(limit=100):
|
|
188
|
+
print(contact["email"])
|
|
189
|
+
|
|
190
|
+
# async
|
|
191
|
+
async for domain in async_client.domains.list_all():
|
|
192
|
+
print(domain["name"])
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
An iterator walks in the list's own order from `after` (or the first page); start it with `before` to walk the other way. It raises the same errors as the methods.
|
|
196
|
+
|
|
197
|
+
## Errors
|
|
198
|
+
|
|
199
|
+
Every error is a `BillionSendError` with the API's error shape, `status_code`, `name` and `message`, plus `request_id`, the API's id of the request (its `x-request-id` header; quote it when asking for support).
|
|
200
|
+
|
|
201
|
+
```python
|
|
202
|
+
from billionsend import BillionSend, BillionSendError, NotFoundError, RateLimitError
|
|
203
|
+
|
|
204
|
+
client = BillionSend()
|
|
205
|
+
try:
|
|
206
|
+
client.domains.get("6a1f1d38-3c55-4a4e-9a57-0f2b3c4d5e6f")
|
|
207
|
+
except NotFoundError:
|
|
208
|
+
print("no such domain")
|
|
209
|
+
except RateLimitError as err:
|
|
210
|
+
print("retry in", err.retry_after)
|
|
211
|
+
except BillionSendError as err:
|
|
212
|
+
print(err.status_code, err.name, err.message, err.request_id)
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
| Status | Exception |
|
|
216
|
+
| --- | --- |
|
|
217
|
+
| 400, 422 | `ValidationError` |
|
|
218
|
+
| 401 | `AuthenticationError` |
|
|
219
|
+
| 403 | `PermissionDeniedError` |
|
|
220
|
+
| 404 | `NotFoundError` |
|
|
221
|
+
| 409 | `ConflictError` |
|
|
222
|
+
| 429 | `RateLimitError` (`retry_after` in seconds) |
|
|
223
|
+
| 5xx | `APIError` |
|
|
224
|
+
| no answer | `APIConnectionError`, and `APITimeoutError` (a subclass) for timeouts; `status_code` and `request_id` are `None` |
|
|
225
|
+
|
|
226
|
+
An answer that is not JSON keeps the same shape, with `name` set to `"application_error"`. `WebhookVerificationError` (`name` `"webhook_verification_error"`) is a `BillionSendError` too.
|
|
227
|
+
|
|
228
|
+
## Retries
|
|
229
|
+
|
|
230
|
+
A request is retried when repeating it is safe: GET, PUT and DELETE, and any request carrying an idempotency key (every send does). It is retried on 429, on 5xx, when no answer came back (connection failure, timeout), and, for a keyed request, on 409 `concurrent_idempotent_requests` (a retry that caught the first attempt still running). The wait is the answer's `Retry-After` when there is one, otherwise exponential backoff with jitter (0.5 s, 1 s, 2 s… up to 8 s). An answer asking to wait more than 60 seconds, such as a used-up daily quota, is raised at once. `max_retries` (default 2) bounds the retries of one call; `0` turns them off.
|
|
231
|
+
|
|
232
|
+
## Configuration
|
|
233
|
+
|
|
234
|
+
| Argument | Environment | Default |
|
|
235
|
+
| --- | --- | --- |
|
|
236
|
+
| `api_key` | `BILLIONSEND_API_KEY` | none (only `agent.signup` works without one) |
|
|
237
|
+
| `base_url` | `BILLIONSEND_BASE_URL` | `https://api.billionsend.com` |
|
|
238
|
+
| `timeout` | | `60` seconds per attempt, or an `httpx.Timeout` |
|
|
239
|
+
| `max_retries` | | `2` |
|
|
240
|
+
| `default_headers` | | none |
|
|
241
|
+
| `http_client` | | an `httpx.Client` / `httpx.AsyncClient` of your own (proxies, transports); the SDK does not close it |
|
|
242
|
+
|
|
243
|
+
Close the client with `client.close()` (`await client.close()`) or use it as a context manager.
|
|
244
|
+
|
|
245
|
+
## Development
|
|
246
|
+
|
|
247
|
+
```bash
|
|
248
|
+
uv sync
|
|
249
|
+
uv run ruff check . && uv run ruff format --check .
|
|
250
|
+
uv run mypy
|
|
251
|
+
uv run pytest
|
|
252
|
+
uv build
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
The SDK is built from a snapshot of the API's OpenAPI document, `openapi/api.openapi.json`. The snapshot is the contract: `scripts/generate.py` writes `src/billionsend/types.py` and the resource modules from it (method names from each `operationId`, idempotency keys where an operation declares the `Idempotency-Key` header, iterators for cursor lists), and the tests validate every request the SDK sends and every response it receives against it through a contract mock (`tests/contract.py`). A coverage test fails when an operation of the snapshot has no SDK method, or when the SDK calls something the snapshot does not declare.
|
|
256
|
+
|
|
257
|
+
When the API changes:
|
|
258
|
+
|
|
259
|
+
```bash
|
|
260
|
+
uv run python scripts/sync_openapi.py # or: --from path/to/api.openapi.json
|
|
261
|
+
uv run python scripts/generate.py
|
|
262
|
+
uv run pytest
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
Whatever fails is what the SDK has to follow. CI runs `scripts/generate.py --check` so the generated code never drifts from the snapshot.
|
|
266
|
+
|
|
267
|
+
## Releasing
|
|
268
|
+
|
|
269
|
+
Publishing is manual; nothing is published on push.
|
|
270
|
+
|
|
271
|
+
1. On PyPI, the owner of the `billionsend` project adds a Trusted Publisher (for the first version, a "pending publisher" under Account → Publishing): owner `billionsend`, repository `billionsend-python`, workflow `release.yml`, environment `pypi`.
|
|
272
|
+
2. Set `version` in `pyproject.toml`, turn the changelog's `Unreleased` heading into that version, commit, then tag and push: `git tag v0.1.0 && git push origin main v0.1.0`.
|
|
273
|
+
3. Actions → `release` → Run workflow, on the version tag. The workflow refuses a branch or a tag that differs from `pyproject.toml`, runs every check, builds the sdist and wheel, and uploads them with PyPI Trusted Publishing (no token stored).
|
|
274
|
+
|
|
275
|
+
Without Trusted Publishing, the same release from a clean checkout of the tag is `uv build && uv publish` with an API token scoped to the `billionsend` project in `UV_PUBLISH_TOKEN`.
|
|
276
|
+
|
|
277
|
+
## License
|
|
278
|
+
|
|
279
|
+
MIT
|