---
title: Rust SDK
description: Use BillionSend from Rust with the billionsend crate.
---

The `billionsend` crate is the BillionSend client for Rust. 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 methods are generated from the API's OpenAPI document. The source is [billionsend/billionsend-rust](https://github.com/billionsend/billionsend-rust) on GitHub.

## Install

Needs Rust 1.85 or newer. The crate is async, on `tokio` and `reqwest`, with TLS through rustls (the `native-tls` feature uses the platform's TLS library instead); `futures-util` drives the list and event streams.

```sh
cargo add billionsend@0.1.2 serde_json futures-util
cargo add tokio --features macros,rt-multi-thread
```

## Send an email

```rust
use billionsend::BillionSend;
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), billionsend::Error> {
    let bs = BillionSend::from_env(); // reads BILLIONSEND_API_KEY

    let sent = bs
        .emails()
        .send(&json!({
            "from": "Acme <hello@acme.dev>",
            "to": ["ana@example.com"],
            "subject": "Welcome to Acme",
            "html": "<p>Glad you are here.</p>",
        }))
        .idempotency_key("welcome/ana")
        .await?;
    println!("{}", sent["id"].as_str().unwrap_or_default());
    Ok(())
}
```

`BillionSend::new("bs_...")` takes the key directly; `BillionSend::builder()` sets the rest with `.api_key`, `.base_url`, `.timeout` (per attempt, default 60 s), `.max_retries`, `.header` and `.http_client` (your own `reqwest::Client`), then `.build()?`. `BILLIONSEND_BASE_URL` overrides the API URL.

## Method names

Each operation is a method named after its id in the [API reference](/docs/api-reference), each dotted segment a call in snake_case: `emails.send` is `bs.emails().send(..)`, `emails.receiving.attachments.list` is `bs.emails().receiving().attachments().list(..)`. `emails.metrics` is `bs.emails().metrics().get()`, beside `links()`, `countries()` and `clients()`.

A method takes the path parameters in order, then the request body: anything that implements `serde::Serialize`, such as a `json!` value, with the API's own field names. It returns a request builder whose setters are the query and header parameters (`.limit(100)`, `.after(id)`, `.batch_validation("strict")`), and awaiting it sends the request. The answer is a `serde_json::Value`; end with `.json::<T>()` to read it into your own `Deserialize` type, or `.raw()` to keep the status and headers.

## Idempotency and retries

The eight sending operations (`emails().send`, `emails().batch`, received-mail replies and forwards, `inboxes().send`, `inboxes().drafts().send`, thread replies and forwards) always send an `Idempotency-Key`. Without `.idempotency_key(..)`, each call makes one up that its retries reuse, so a retry after a timeout never sends twice; your own key also makes a repeat from another process safe.

Failures worth retrying are retried twice by default: 429, 5xx, timeouts, network errors, and the `409 concurrent_idempotent_requests` answered while the first attempt with the same key is still running. Only requests safe to repeat are retried: `GET`, `PUT`, `DELETE` and the sending operations. The client waits as `Retry-After` asks, and returns the error instead when it asks for more than a minute; otherwise it backs off exponentially from 500 ms to 8 s, less up to a quarter of jitter. Every request builder also takes `.timeout(..)`, `.max_retries(..)` and `.header(..)` for that call.

## Errors

A failed call returns a `billionsend::Error`, one variant per kind: `Validation` (400, 422), `Authentication` (401, or no key configured), `PermissionDenied` (403), `NotFound` (404), `Conflict` (409), `RateLimit` (429, with `retry_after()` in seconds), `Server` (5xx), `Api` (any other status, or an answer that is not the expected JSON), `Connection` (no answer), `Timeout` (the attempt timed out), `WebhookVerification` and `Application` (made up by the client without a call, such as an empty path parameter). Every variant has `status_code()`, `name()` (the API's error name), `message()` and `request_id()`, the answer's `x-request-id`, which is the request's id on the dashboard's Logs page.

```rust
use billionsend::Error;

match bs.emails().get(id).await {
    Ok(email) => println!("{}", email["last_event"]),
    Err(Error::NotFound(_)) => println!("no such email"),
    Err(error) => eprintln!(
        "{:?} {}: {} (request {:?})",
        error.status_code(),
        error.name(),
        error.message(),
        error.request_id(),
    ),
}
```

## Lists

List methods return one page. Every cursor list also has `.into_stream()`, a stream of its items that fetches the next pages as it goes, backward when `.before(..)` is set:

```rust
use futures_util::TryStreamExt;

let mut contacts = bs.contacts().list().limit(100).into_stream();
while let Some(contact) = contacts.try_next().await? {
    println!("{}", contact["email"].as_str().unwrap_or_default());
}
```

## An agent's inbox

Wait for new mail on the [event stream](/docs/inboxes) and reply in its thread:

```rust
use billionsend::InboxStreamItem;
use futures_util::StreamExt;
use serde_json::json;

let mut events = bs
    .inboxes()
    .events()
    .stream_inbox("support@acme.dev")
    .types("inbox.email.received")
    .await?;

while let Some(item) = events.next().await {
    // An error here: reconnecting ran out, or the key stopped working.
    let event = match item? {
        InboxStreamItem::Event(event) => event,
        // Events may be missing: read the threads again.
        InboxStreamItem::Gap(_) => continue,
    };
    let data = &event.data;
    let (Some(inbox_id), Some(thread_id), Some(email_id)) = (
        data["inbox_id"].as_str(),
        data["data"]["thread_id"].as_str(),
        data["data"]["email_id"].as_str(),
    ) else {
        continue;
    };
    bs.inboxes()
        .threads()
        .emails()
        .reply(inbox_id, thread_id, email_id, &json!({ "text": "Thanks, we are on it." }))
        .idempotency_key(format!("reply/{email_id}"))
        .await?;
}
```

The stream reconnects with `Last-Event-ID` when the connection drops and replays what it missed; keep `events.last_event_id()` and pass it back with `.last_event_id(..)` to resume after a restart. An `InboxStreamItem::Gap` comes once when the stream resumes from more than 24 hours back. `.max_reconnects(..)` (failed reconnects in a row before giving up, default 5), `.reconnect_delay(..)` and `.reconnect(false)` tune reconnecting. One inbox's stream ends after that inbox is deleted or expires; `bs.inboxes().events().stream()` follows every inbox of the team, with a team-wide key.

## Verify webhooks

`verify_webhook` checks a [webhook](/docs/concepts/webhooks) delivery's signature and timestamp with the endpoint's `whsec_` secret and returns the parsed event; anything wrong is an `Error::WebhookVerification`. Pass the body exactly as it arrived. The headers can be an `http` `HeaderMap`, as in axum, a `HashMap` or a list of pairs:

```rust
use axum::body::Bytes;
use axum::http::{HeaderMap, StatusCode};
use axum::{Router, routing::post};

async fn webhook(headers: HeaderMap, body: Bytes) -> StatusCode {
    let secret = std::env::var("BILLIONSEND_WEBHOOK_SECRET").unwrap_or_default();
    match billionsend::verify_webhook(&body, &headers, &secret) {
        Ok(event) => {
            println!("{}", event["type"]);
            StatusCode::NO_CONTENT
        }
        Err(_) => StatusCode::BAD_REQUEST,
    }
}

fn app() -> Router {
    Router::new().route("/webhooks/billionsend", post(webhook))
}
```

A delivery older than five minutes is refused (`WebhookVerifier::new(secret)?.tolerance(..)` sets another window), and during a secret rotation either secret verifies.
