---
title: Java SDK
description: Use BillionSend from Java with the com.billionsend:billionsend-java package.
---

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

## Install

Needs Java 17 or newer. Requests go through the JDK's `java.net.http.HttpClient`, and the one runtime dependency is `jackson-databind`. With Maven:

```xml
<dependency>
  <groupId>com.billionsend</groupId>
  <artifactId>billionsend-java</artifactId>
  <version>0.1.0</version>
</dependency>
```

With Gradle:

```kotlin
implementation("com.billionsend:billionsend-java:0.1.2")
```

## Send an email

```java
import com.billionsend.BillionSend;
import com.billionsend.RequestOptions;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
import java.util.Map;

public class Welcome {
  public static void main(String[] args) {
    BillionSend client = new BillionSend(); // reads BILLIONSEND_API_KEY

    JsonNode sent =
        client.emails().send(
            Map.of(
                "from", "Acme <hello@acme.dev>",
                "to", List.of("ana@example.com"),
                "subject", "Welcome to Acme",
                "html", "<p>Glad you are here.</p>"),
            RequestOptions.builder().idempotencyKey("welcome/ana").build());

    System.out.println(sent.get("id").asText());
  }
}
```

`new BillionSend("bs_...")` takes the key directly. `BillionSend.builder()` sets the rest: `apiKey`, `baseUrl`, `timeout` (per attempt, default 60 s), `maxRetries`, `header` and `httpClient` (your own `java.net.http.HttpClient`). `BILLIONSEND_BASE_URL` overrides the API URL. A client is thread-safe: make one and share it.

## Method names

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

A method takes the path parameters in order, the request body, the query parameters, then a `RequestOptions`; shorter overloads leave out what is optional. A body is anything Jackson can write: a `Map`, a `JsonNode` or a class of your own. The query is a `Map<String, ?>` whose `null` values are left out and whose lists go comma-separated. Every answer is a Jackson `JsonNode` with the API's own field names, so the API reference describes it field for field.

## 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 `idempotencyKey`, 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`, the sending operations and any request you give an idempotency key. The client waits as `Retry-After` asks, up to a minute (a longer wait throws at once), and otherwise backs off exponentially from 0.5 s to 8 s. The last argument of every method is a `RequestOptions` whose builder takes `idempotencyKey`, `header`, `timeout`, `maxRetries` and `batchValidation` for that call.

## Errors

A failed call throws `ValidationException` (400, 422), `AuthenticationException` (401, or no key configured), `PermissionDeniedException` (403), `NotFoundException` (404), `ConflictException` (409), `RateLimitException` (429, with `getRetryAfter()` in seconds), `ApiException` (5xx), `ApiConnectionException` (no answer) or `ApiTimeoutException` (the attempt timed out). All are unchecked, in `com.billionsend`, and extend `BillionSendException`, with `getStatusCode()` (`null` when no answer came), `getName()` (the API's error name), `getMessage()` and `getRequestId()`, the answer's `x-request-id`, which is the request's id on the dashboard's Logs page.

```java
import com.billionsend.BillionSendException;
import com.billionsend.NotFoundException;

try {
  JsonNode email = client.emails().get(id);
} catch (NotFoundException e) {
  // no such email
} catch (BillionSendException e) {
  System.err.printf(
      "%s %s: %s (request %s)%n",
      e.getStatusCode(), e.getName(), e.getMessage(), e.getRequestId());
}
```

## Lists

List methods return one page. Every cursor list also has a `listAll` (thread search: `searchAll`) that fetches the next pages as the loop asks for them, backward when `before` is set; `.stream()` gives the same items as a `Stream<JsonNode>`:

```java
for (JsonNode contact : client.contacts().listAll(Map.of("limit", 100))) {
  System.out.println(contact.get("email").asText());
}
```

## An agent's inbox

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

```java
import com.billionsend.EventStream;
import com.billionsend.InboxStreamItem;
import com.billionsend.StreamGapEvent;

Map<String, ?> query = Map.of("types", "inbox.email.received");
try (EventStream stream = client.inboxes().events().streamInbox("support@acme.dev", query)) {
  for (InboxStreamItem item : stream) {
    if (item instanceof StreamGapEvent) {
      continue; // events may be missing: read the threads again
    }
    JsonNode event = item.data();
    String emailId = event.path("data").path("email_id").asText();
    client.inboxes().threads().emails().reply(
        event.path("inbox_id").asText(),
        event.path("data").path("thread_id").asText(),
        emailId,
        Map.of("text", "Thanks, we are on it."),
        RequestOptions.builder().idempotencyKey("reply/" + emailId).build());
  }
}
```

The stream reconnects with `Last-Event-ID` when the connection drops and replays what it missed; keep `stream.lastEventId()` and pass it back with `EventStreamOptions.builder().lastEventId(...)` to resume after a restart. A `StreamGapEvent` comes once when the stream resumes from more than 24 hours back. `maxReconnects` (default 5, after which the loop throws an `ApiConnectionException`), `reconnectDelay` and `reconnect(false)` tune reconnecting. One inbox's stream ends after that inbox is deleted or expires; `client.inboxes().events().stream()` follows every inbox the key can read.

## Verify webhooks

`WebhookVerifier.verify` checks a [webhook](/docs/concepts/webhooks) delivery's signature and timestamp with the endpoint's `whsec_` secret and returns the parsed event, or throws a `WebhookVerificationException`. Pass the body exactly as it arrived, and the headers as a map:

```java
import com.billionsend.WebhookVerificationException;
import com.billionsend.WebhookVerifier;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;

HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/webhooks/billionsend", exchange -> {
  byte[] body = exchange.getRequestBody().readAllBytes();
  String secret = System.getenv("BILLIONSEND_WEBHOOK_SECRET");
  int status = 204;
  try {
    JsonNode event = WebhookVerifier.verify(body, exchange.getRequestHeaders(), secret);
    System.out.println(event.get("type").asText());
  } catch (WebhookVerificationException e) {
    status = 400;
  }
  exchange.sendResponseHeaders(status, -1);
  exchange.close();
});
server.start();
```

A delivery older than five minutes is refused, and during a secret rotation either secret verifies.
