# Java SDK

Install the Mailset Java SDK, send email, verify webhooks and handle errors, with examples that run.

- **Every public command**: 238 commands, each a typed method
- **No dependencies**: Nothing else to install beside it
- **Typed throughout**: Immutable classes, each with a builder
- **Sync and async**: Mailset, and async() for futures
- **Retries built in**: Two more tries, and a send never doubles
- **Timeouts per try**: 30 seconds a try, then tried again

## Requirements

- Java 17 or later

## Install

Maven:

```xml
<dependency>
    <groupId>app.mailset</groupId>
    <artifactId>java</artifactId>
    <version>0.7.0</version>
</dependency>
```

Gradle:

```kotlin
implementation("app.mailset:java:0.7.0")
```

## Create a client

One client holds one `MAILSET_KEY`. Make it when your server starts and use it for every call.

### Example

```java
import app.mailset.Mailset;

// One client for the whole server, from
// MAILSET_KEY in the environment. Safe to share
// between threads; nothing is sent until you
// call a method.
Mailset mailset = Mailset.fromEnv();
```

### Pass the key in

Where your app keeps its secrets elsewhere, hand the key to the client yourself. A token goes the same way.

```java
import app.mailset.Mailset;

// From your secret store or config, never in the code.
// Or .token(…) with an API token.
Mailset mailset = Mailset.builder()
        .key(config.mailsetKey())
        .build();
```

### Options

Everything has a default. Name a credential, an org, how long a try may take and how often a call is tried again, only where yours differ.

```java
import app.mailset.Mailset;
import java.time.Duration;

Mailset mailset = Mailset.builder()
        // Or .token(…) for an API token.
        .key(System.getenv("MAILSET_KEY"))
        // MAILSET_API, else the key's, unless told.
        .baseUrl("https://mailset.app")
        // For a person in more than one org.
        .org("org_7c2e9a4f")
        // Each try may take 10 seconds. A network
        // failure, a timeout or a 5xx is tried 3
        // more times, waiting longer each time.
        .timeout(Duration.ofSeconds(10))
        .maxRetries(3)
        // A command that needs a passkey waits
        // for someone to approve it.
        .onApproval(approval -> System.out.println(
                "Approve it: " + approval.url()))
        .build();
```

More: [Authentication](https://mailset.app/docs/authentication)

## Send

Send one message and get its receipt. A message Mailset refuses is an error with a code, never a silent drop.

### Example

```java
import app.mailset.Mailset;
import app.mailset.Message;
import app.mailset.Sent;

// Reads MAILSET_KEY from the environment.
Mailset mailset = Mailset.fromEnv();

Sent sent = mailset.send(Message.builder()
        .from("Acme <hello@example.com>")
        .to("ana@example.org")
        .subject("Your Acme code")
        .text("Your code is 123456.")
        .html("<p>Your code is <b>123456</b>.</p>")
        .deliverBy("10m")
        .build());

System.out.println(sent.id() + " " + sent.status());
```

More: [Give sign-in codes a deadline](https://mailset.app/docs/recipes/deadlines), [Honor unsubscribes and complaints](https://mailset.app/docs/recipes/unsubscribes), [Handle skipped recipients](https://mailset.app/docs/recipes/skipped), [Guide for Java](https://mailset.app/send-email/java)

## Send many

Send several messages in one call and get one result per message, in the same order. A refused message never stops the rest.

### Example

```java
import app.mailset.Mailset;
import app.mailset.Message;
import app.mailset.NotSent;
import app.mailset.SendResult;
import app.mailset.Sent;
import java.util.List;

// Reads MAILSET_KEY from the environment.
Mailset mailset = Mailset.fromEnv();

List<SendResult> results = mailset.send(List.of(
        Message.builder()
                .from("Acme <hello@example.com>")
                .to("ana@example.org")
                .subject("Your invoice")
                .text("Invoice 8842 is ready.")
                .build(),
        Message.builder()
                .from("Acme <hello@example.com>")
                .to("ben@example.org")
                .subject("Your invoice")
                .text("Invoice 8843 is ready.")
                .build()));

for (SendResult result : results) {
    if (result instanceof Sent sent) {
        System.out.println(sent.id());
    } else if (result instanceof NotSent no) {
        System.err.println(no.messageId()
                + " " + no.error().getCode());
    }
}
```

More: [Send many messages at once](https://mailset.app/docs/recipes/batches)

## Promotional email

Send a newsletter or an offer with `mode: 'promotional'`. `{{mailset_unsubscribe}}` is a placeholder Mailset fills in for each message, with a signed one-click unsubscribe link unique to that recipient and that message. You never generate the link, and Mailset adds the matching `List-Unsubscribe` and `List-Unsubscribe-Post` headers itself.

### Example

```java
import app.mailset.Mailset;
import app.mailset.Message;
import app.mailset.Sent;

// Reads MAILSET_KEY from the environment.
Mailset mailset = Mailset.fromEnv();

String text = String.join("\n",
        "Three new things this month.",
        "",
        "Leave this list: {{mailset_unsubscribe}}");

String html = String.join("\n",
        "<p>Three new things this month.</p>",
        "<a href=\"{{mailset_unsubscribe}}\">"
                + "Leave this list</a>");

Sent sent = mailset.send(Message.builder()
        .from("Acme News <news@news.example.com>")
        .to("ana@example.org")
        .subject("What shipped in March")
        .text(text)
        .html(html)
        .mode(Message.Mode.PROMOTIONAL)
        .build());

System.out.println(sent.id() + " " + sent.skipped());
```

### What Ana receives

Headers Mailset adds:

```text
List-Unsubscribe: <https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc>
List-Unsubscribe-Post: List-Unsubscribe=One-Click
```

The text part:

```text
Three new things this month.

Leave this list: https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc
```

The HTML part:

```html
<p>Three new things this month.</p>
<a href="https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc">Leave this list</a>
```

A sample link. Mailset makes a new one for every message.

### What Ana receives without the placeholder

The text part:

```text
Three new things this month.

Unsubscribe: https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc
```

The HTML part:

```html
<p>Three new things this month.</p><p><a href="https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc">Unsubscribe</a></p>
```

Mailset adds the last line of each part. The headers are the same.

More: [Honor unsubscribes and complaints](https://mailset.app/docs/recipes/unsubscribes), [Handle skipped recipients](https://mailset.app/docs/recipes/skipped)

## Idempotency

Name a send with `idempotencyKey`, and sending it again after a timeout or a crash can’t send it twice.

### Example

```java
import app.mailset.Mailset;
import app.mailset.Message;
import app.mailset.Sent;

// Reads MAILSET_KEY from the environment.
Mailset mailset = Mailset.fromEnv();

Message receipt = Message.builder()
        .from("Acme <hello@example.com>")
        .to("ana@example.org")
        .subject("Your receipt")
        .text("Thanks for your order.")
        .idempotencyKey("receipt-8842")
        .build();

Sent first = mailset.send(receipt);
// After a timeout or a crash, send it again.
// The same key answers the first receipt,
// and nothing goes out twice.
Sent again = mailset.send(receipt);

System.out.println(first.id().equals(again.id()));
```

More: [Retry without sending twice](https://mailset.app/docs/recipes/retries)

## Check the key

Ask what the key may do now. Call it when your server starts and once a day: each call keeps the key alive.

### Example

```java
import app.mailset.Mailset;
import app.mailset.model.GrantDomain;
import app.mailset.model.GrantMailbox;
import app.mailset.model.KeyStatus;
import java.time.Instant;

// Reads MAILSET_KEY from the environment.
Mailset mailset = Mailset.fromEnv();

// When the server starts, and once a day.
KeyStatus status = mailset.key().check();

status.paused().ifPresent(why ->
        System.err.println("Paused: " + why));
System.out.println("Works until "
        + Instant.ofEpochMilli(status.expiresAt()));
// A mailbox key sends as its mailbox.
for (GrantMailbox box : status.mailboxes())
    warn(box.address(), box.sending());
// A domain key sends as the addresses it names.
for (GrantDomain domain : status.domains()) {
    String as = domain.from()
            .map(from -> String.join(", ", from))
            .orElse("any address");
    System.out.println(
            domain.name() + " sends as " + as);
    warn(domain.name(), domain.sending());
}
```

More: [Keep a key alive](https://mailset.app/docs/recipes/keys)

## Delivery search

Look up what became of the mail this key sent, one line per recipient. For a support question or a nightly check.

### Example

```java
import app.mailset.DeliveryLine;
import app.mailset.DeliveryPage;
import app.mailset.DeliverySearch;
import app.mailset.Mailset;
import java.time.LocalDate;

// Reads MAILSET_KEY from the environment.
Mailset mailset = Mailset.fromEnv();

// Did Ana get her receipt?
DeliveryPage page = mailset.delivery().search(
        DeliverySearch.builder()
                .recipient("ana@example.org")
                .since(LocalDate.of(2026, 11, 30))
                .build());

for (DeliveryLine line : page.lines()) {
    System.out.println(line.status() + " "
            + line.reason().orElse(""));
}
// Pass next back as cursor for the page after.
page.next().ifPresent(System.out::println);
```

More: [Handle bounces](https://mailset.app/docs/recipes/bounces)

## Webhooks

Check that a request came from Mailset and read its events. It needs no key and no client, so a service that only receives events uses it alone.

### Example

```java
import app.mailset.MailEvent;
import app.mailset.MailsetException;
import app.mailset.Webhooks;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.util.List;

// POST /mailset/events, on the JDK's own server.
static void events(HttpExchange exchange)
        throws IOException {
    // The signature covers the body exactly as it
    // came: read its bytes.
    byte[] body =
            exchange.getRequestBody().readAllBytes();
    String signature = exchange.getRequestHeaders()
            .getFirst("Mailset-Signature");
    int status = 204;
    try {
        List<MailEvent> events =
                Webhooks.verify(body, signature, secret);
        for (MailEvent event : events) {
            if (event instanceof MailEvent.Bounced b
                    && b.bounce().kind().equals("hard"))
                stopWritingTo(b.recipient());
        }
        // 2xx once the events are kept. Until then
        // Mailset posts the batch again.
    } catch (MailsetException error) {
        status = 401;
    }
    exchange.sendResponseHeaders(status, -1);
    exchange.close();
}
```

### In a web framework

The signature covers the body exactly as it arrived. Read the raw body before anything parses it, and hand that to the check: a body parsed as JSON and written out again no longer matches.

```java
import app.mailset.MailEvent;
import app.mailset.MailsetException;
import app.mailset.Webhooks;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

// The signature covers the body exactly as it came:
// take it as bytes. A mapped object would lose the
// bytes it was made over.
@PostMapping("/mailset/events")
public ResponseEntity<String> events(
        @RequestBody byte[] body,
        @RequestHeader(value = "Mailset-Signature",
                required = false) String signature) {
    try {
        List<MailEvent> events =
                Webhooks.verify(body, signature, secret);
        for (MailEvent event : events) {
            if (event instanceof MailEvent.Bounced b
                    && b.bounce().kind().equals("hard"))
                stopWritingTo(b.recipient());
        }
        // 2xx once the events are kept. Until then
        // Mailset posts the batch again.
        return ResponseEntity.noContent().build();
    } catch (MailsetException error) {
        return ResponseEntity.status(401)
                .body(error.getCode());
    }
}
```

More: [Webhooks](https://mailset.app/docs/webhooks), [Handle bounces](https://mailset.app/docs/recipes/bounces), [Guide for Spring Boot](https://mailset.app/send-email/spring-boot)

## Errors

Every refusal is one kind of error. Branch on its `code`, which never changes, and show its `message` to people.

### Example

```java
import app.mailset.Mailset;
import app.mailset.MailsetException;
import app.mailset.Message;
import java.time.Instant;

// Reads MAILSET_KEY from the environment.
Mailset mailset = Mailset.fromEnv();

try {
    mailset.send(Message.builder()
            .from("Acme <hello@example.com>")
            .to("ana@example.org")
            .subject("Your Acme code")
            .text("Your code is 123456.")
            .deliverBy("10m")
            .build());
} catch (MailsetException error) {
    Long retryAt = error.getRetryAt();
    String refusal = error.getRefusal();
    if (error.getCode().equals("limit_reached")
            && retryAt != null) {
        System.out.println("Try at "
                + Instant.ofEpochMilli(retryAt));
    } else if ("recipient".equals(refusal)) {
        System.out.println("Ask them to check it.");
    } else {
        // Its string form ends with the docs for
        // the code and where to ask.
        System.err.println(error);
    }
}
```

### Retries and timeouts

A network failure or a 5xx answer is tried again, twice unless you set `maxRetries`, waiting longer each time. One try may take 30 seconds unless you set `timeout`. A refusal is never tried again: the same request gets the same answer.

More: [Errors and limits](https://mailset.app/docs/errors)

## Build the message yourself

Get the message a send would build, without sending it: for a queue of your own, or a call to the API from another service.

### Example

```java
import app.mailset.Message;
import app.mailset.RawMessage;

RawMessage raw = Message.builder()
        .from("Acme <hello@example.com>")
        .to("ana@example.org")
        .subject("Your Acme code")
        .text("Your code is 123456.")
        .build()
        .toRaw();

// The data that messages.submit takes.
String data = raw.base64();

System.out.println(raw.messageId());
System.out.println(data.length());
```

More: [messages.submit](https://mailset.app/docs/api/messages#messages.submit)

## Names

A method is named for its command. Java can’t spell these, so each has a name that says what it does:

- [`billing.switch`](https://mailset.app/docs/api/billing#billing.switch) is `switchPlan`: `switch` is a Java keyword.
- [`addresses.default`](https://mailset.app/docs/api/addresses#addresses.default) is `setDefault`: `default` is a Java keyword.
- [`contacts.import`](https://mailset.app/docs/api/contacts#contacts.import) is `importContacts`: `import` is a Java keyword.
- [`rules.import`](https://mailset.app/docs/api/rules#rules.import) is `importRules`: `import` is a Java keyword.

## Version and licence

This page is for version 0.7.0 of the Java SDK.

You may use the SDK and change it in your own apps and services, to call Mailset. You may not publish it or pass it on, by itself or inside another library.

Something missing, or not working as this page says? Ask us at https://mailset.app/support, or run `mailset feedback "<message>"` in a terminal.

---

© 2026 Intenseloop, Inc. Mailset’s site, docs and guides are copyrighted. You may read them and use their code to build with Mailset. Don’t republish them or use them to build a copy of Mailset. Terms: https://mailset.app/terms#content