---
title: Elixir SDK
description: Use BillionSend from Elixir with the billionsend Hex package.
---

The `billionsend` package is the BillionSend client for Elixir. 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. The source is [billionsend/billionsend-elixir](https://github.com/billionsend/billionsend-elixir) on GitHub.

## Install

Needs Elixir 1.18 or newer and OTP 25 or newer. The package has no dependencies: it uses `:httpc` and `:ssl` from OTP and Elixir's built-in `JSON`.

```elixir
def deps do
  [{:billionsend, "~> 0.1"}]
end
```

## Send an email

```elixir
client = BillionSend.client()  # reads BILLIONSEND_API_KEY

{:ok, sent} =
  BillionSend.Emails.send(
    client,
    %{
      from: "Acme <hello@acme.dev>",
      to: ["ana@example.com"],
      subject: "Welcome to Acme",
      html: "<p>Glad you are here.</p>"
    },
    idempotency_key: "welcome/ana"
  )

IO.puts(sent["id"])
```

`BillionSend.client(api_key: "bs_...")` takes the key directly; `base_url:`, `timeout:` (milliseconds per attempt, default `60_000`), `max_retries:`, `default_headers:` and `transport:` (a `{module, state}` implementing `BillionSend.Transport`, to send through your own HTTP layer) set the rest. `BILLIONSEND_BASE_URL` overrides the API URL. A client is a plain struct: build it once and pass it to every call, from any process.

## Method names

Each operation is a function named after its id in the [API reference](/docs/api-reference): the dotted path's groups make the module and the last segment the function, camelCase written in snake_case. `emails.send` is `BillionSend.Emails.send/3`, `emails.receiving.attachments.list` is `BillionSend.Emails.Receiving.Attachments.list/3`, and `agent.claimEmail` is `BillionSend.Agent.claim_email/2`. `emails.metrics` is `BillionSend.Emails.metrics/2`, beside `BillionSend.Emails.Metrics.links/2`, `.countries/2` and `.clients/2`.

A function takes the client, the path parameters in order, the request body as a map, then a keyword list of options: the query and header parameters (`BillionSend.Emails.list(client, limit: 50)`; a list parameter takes a list), `:extra_headers` and `:timeout`, and on the sending functions `:idempotency_key`. A body the operation does not require may be left out. An unknown option, or a missing required one, raises `ArgumentError` before anything is sent. Every function returns `{:ok, answer}` or `{:error, error}`, and its `!` twin (`BillionSend.Emails.send!/3`) returns the answer or raises. Answers are the API's JSON decoded into maps with string keys and the API's own field names (`sent["id"]`), so the API reference describes them field for field. `BillionSend.Client.request(client, "GET", "/path", query: [...])` reaches anything the functions do not cover.

## Idempotency and retries

The eight sending functions (`Emails.send`, `Emails.batch`, `Emails.Receiving.reply` and `.forward`, `Inboxes.send`, `Inboxes.Drafts.send`, `Inboxes.Threads.Emails.reply` and `.forward`) always send an `Idempotency-Key`. Without `idempotency_key:`, each call makes up one (a UUID) that its retries reuse, so a retry after a dropped connection never sends twice; your own key also makes a repeat from another process safe. The same key with a different request is refused with a `BillionSend.ConflictError`.

Failures worth retrying are retried twice by default: 429, 5xx, no answer (connection failure, timeout), 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 any request carrying an idempotency key, as every send does. The client waits as `Retry-After` asks and returns the error at once when it asks for more than a minute; otherwise it backs off exponentially from 0.5 s to 8 s, with jitter. `max_retries:` is set on the client (`0` turns retries off), and the calling process sleeps between attempts.

## Errors

A failed call returns `{:error, error}` with an exception struct: `BillionSend.ValidationError` (400, 422), `AuthenticationError` (401, or no key configured, with `name` set to `missing_api_key` before anything is sent), `PermissionDeniedError` (403), `NotFoundError` (404), `ConflictError` (409), `RateLimitError` (429, with `retry_after` in seconds), `APIError` (5xx), `APIConnectionError` (no answer) or `APITimeoutError` (the attempt timed out). `BillionSend.Error` is any other status. Each carries `status_code` (`nil` when there was no answer), `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. `BillionSend.Errors.error?/1` tells any of them apart from other terms.

```elixir
case BillionSend.Emails.get(client, id) do
  {:ok, email} -> email["subject"]
  {:error, %BillionSend.NotFoundError{}} -> nil
  {:error, %BillionSend.RateLimitError{retry_after: seconds}} -> {:retry_in, seconds}
  {:error, error} -> Logger.error("#{error.status_code} #{error.name}: #{error.message} (request #{error.request_id})")
end
```

## Lists

List functions return one page. Every cursor list also has an `_all` function (`search_all` for thread search) that returns a lazy `Stream`, fetching the next pages as it goes, backward when `:before` is set:

```elixir
client
|> BillionSend.Contacts.list_all(limit: 100)
|> Enum.each(&IO.puts(&1["email"]))
```

## An agent's inbox

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

```elixir
alias BillionSend.{Inboxes, InboxStreamEvent}

{:ok, events} = Inboxes.Events.stream_inbox(client, "support@acme.dev", types: "inbox.email.received")

events
|> Stream.filter(&match?(%InboxStreamEvent{}, &1))  # a StreamGapEvent: events may be missing, read the threads again
|> Enum.each(fn %InboxStreamEvent{data: %{"inbox_id" => inbox_id, "data" => data}} ->
  %{"thread_id" => thread_id, "email_id" => email_id} = data

  Inboxes.Threads.Emails.reply(
    client,
    inbox_id,
    thread_id,
    email_id,
    %{text: "Thanks, we are on it."},
    idempotency_key: "reply/#{email_id}"
  )
end)
```

`stream_inbox/3` opens the stream first, so a refused stream (a revoked key, a key held to one inbox asking for the team's stream) is an `{:error, error}` at once; what it returns is a lazy `Enumerable` of `BillionSend.InboxStreamEvent` structs (`id`, `event` such as `"inbox.email.received"`, and `data`, the webhook payload's `"type"`, `"created_at"`, `"inbox_id"` and `"data"`) and `BillionSend.StreamGapEvent` structs. The stream reconnects with `Last-Event-ID` when the connection drops and replays what it missed; keep the `id` of the last event you handled and pass it back as `last_event_id:` to resume after a restart. A `StreamGapEvent` comes once when the stream resumes from more than 24 hours back. `max_reconnects:` (default 5 failed reconnects in a row) tunes reconnecting, which waits a second, or what the server's `retry` field asks, before each attempt; past it the enumeration raises the API's error for the last attempt, or `BillionSend.APIConnectionError` when it got no answer. One inbox's stream ends after that inbox is deleted or expires; `BillionSend.Inboxes.Events.stream/2` follows every inbox the key can read. Enumerate a stream once, in the process that opened it: halting the enumeration (`Enum.take/2`, `Stream.take_while/2`) closes the connection.

## Verify webhooks

`BillionSend.verify_webhook/4` checks a [webhook](/docs/concepts/webhooks) delivery's signature and timestamp with the endpoint's `whsec_` secret and returns `{:ok, event}` with the parsed event, or `{:error, %BillionSend.WebhookVerificationError{}}`. Pass the body exactly as it arrived, before any JSON parsing; the headers can be a map or a list of pairs such as `conn.req_headers`, with names in any case:

```elixir
# Phoenix: keep the raw body (a Plug.Parsers :body_reader that stores it in conn.assigns)
def create(conn, _params) do
  case BillionSend.verify_webhook(conn.assigns.raw_body, conn.req_headers, webhook_secret()) do
    {:ok, %{"type" => "email.bounced", "data" => %{"email_id" => id}}} ->
      mark_bounced(id)
      send_resp(conn, 204, "")

    {:ok, _event} ->
      send_resp(conn, 204, "")

    {:error, %BillionSend.WebhookVerificationError{}} ->
      send_resp(conn, 400, "")
  end
end
```

A delivery older than five minutes is refused (`tolerance:`, in seconds, changes that), and during a secret rotation either secret verifies. `verify_webhook!/4` returns the event or raises; a secret that is not a `whsec_` secret raises `ArgumentError`.
