# Send Email with Java: A Complete API Tutorial

> Send email with Java using HttpClient and an email API instead of Jakarta Mail: templates, attachments, batches, safe retries and a Spring Boot example.

Canonical: https://www.cresca.xyz/blog/send-email-java
Author: Lalit Kumar Jangid
Published: 2026-10-27
Last updated: 2026-10-30

Most Java code that sends mail still goes through Jakarta Mail (the old JavaMail): a `Session`, a `Transport`, SMTP credentials and a server at the other end. If you want to **send email with Java** without any of that, the JDK already ships what you need. `java.net.http.HttpClient` posts one JSON request to Cresca, you get an email id back, and the message leaves from your verified domain within seconds. Below: a single-file example, a thread-safe client, templates, attachments, batches and Spring Boot.

**TL;DR**

- Build one `java.net.http.HttpClient` (in the JDK since Java 11) and POST JSON to `https://api.cresca.xyz/api/v1/emails`.
- Send `Authorization: Bearer <key>` and a body with from, to, subject and html.
- Catch `IOException`, retry 429 and 5xx, and send an `Idempotency-Key` so a retry can't deliver twice.
- Batch up to 100 emails per request.

## What you need on the JVM

1. **JDK 17 or newer.** The first example uses a text block, so it won't compile on Java 11.
2. **Jackson** (`com.fasterxml.jackson.core:jackson-databind`) for the reusable client. Spring Boot web projects already include it.
3. **Three things done in Cresca:** your domain verified ([Sending Domains](https://app.cresca.xyz/sending-domains)), a sender address on that domain like `hello@acme.com`, and a *Sending access* key ([API keys](https://app.cresca.xyz/api-keys)). The [email API quickstart](https://www.cresca.xyz/docs/quickstart) covers all three.
4. **The key in the environment** as `CRESCA_API_KEY`. Cresca displays the `cr_live_` key a single time; copy it into your secret store, not a properties file in Git.

## Send email with Java: the basic request

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class SendEmail {
    public static void main(String[] args) throws Exception {
        String json = """
            {
              "from": "Acme <hello@acme.com>",
              "to": "ana@example.com",
              "subject": "Welcome to Acme",
              "html": "<p>Hi Ana, your account is ready.</p>"
            }
            """;

        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.cresca.xyz/api/v1/emails"))
            .timeout(Duration.ofSeconds(10))
            .header("Authorization", "Bearer " + System.getenv("CRESCA_API_KEY"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(json))
            .build();

        HttpResponse<String> response = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println(response.statusCode() + " " + response.body());
    }
}
```

Run it with `java SendEmail.java`; the launcher compiles single-file programs, so there is no build step. You should see `200` followed by `{"id":"4ef9a417-..."}`. Leave out `text` and Cresca writes the plain-text alternative itself. Text blocks are fine for fixed test data. Once a name or address comes from a user, let a JSON library write the body, because hand-built JSON breaks on the first quote or newline.

## A reusable Java client with retries

An `HttpClient` is immutable once built and keeps its own connection pool, so a service should create one and share it. `CrescaClient` does that and adds three things production code needs:

- **An `Idempotency-Key` per email.** When the response is lost after Cresca has taken the email, the retry reuses the key and Cresca replays its first answer rather than delivering twice. A key stays valid for 24 hours. Derive it from the business event (`welcome/user-123`, `invoice/inv-2026-0042`), never from `System.currentTimeMillis()` or `UUID.randomUUID()`. Details in [idempotency](https://www.cresca.xyz/docs/idempotency).
- **Two kinds of failure, handled separately.** `HttpClient.send` throws `IOException` when the network fails, and `HttpTimeoutException` is a subclass, so one catch covers timeouts as well. Those get retried. An HTTP error response throws nothing; you get a status code, and the client retries only 429 `rate_limit_exceeded` and 5xx, sleeping for `retry-after` when Cresca sends it and backing off exponentially when it doesn't. Other 4xx errors would fail again, so they are thrown at once.
- **An exception you can switch on.** Jackson reads the error body's `name` (say, `validation_error`) and `message`. `CrescaException` is unchecked and exposes `status` and `name`. Compare on `name`, since `message` may be reworded.

```java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;

/** A small client for the Cresca email API. Safe to share between threads. */
public class CrescaClient {
    private static final String API_URL = "https://api.cresca.xyz/api/v1";
    private static final int ATTEMPTS = 4;

    private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
    private final ObjectMapper json = new ObjectMapper();
    private final String apiKey;

    public CrescaClient(String apiKey) {
        this.apiKey = apiKey;
    }

    public JsonNode post(String path, Object payload, String idempotencyKey)
            throws IOException, InterruptedException {
        HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(API_URL + path))
            .timeout(Duration.ofSeconds(10))
            .header("Authorization", "Bearer " + apiKey)
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(json.writeValueAsString(payload)));
        if (idempotencyKey != null) {
            builder.header("Idempotency-Key", idempotencyKey);
        }
        HttpRequest request = builder.build();

        for (int attempt = 1; ; attempt++) {
            HttpResponse<String> response;
            try {
                response = http.send(request, HttpResponse.BodyHandlers.ofString());
            } catch (IOException e) {
                // Network error or timeout: the idempotency key makes a retry safe.
                if (attempt == ATTEMPTS) throw e;
                Thread.sleep(backoff(attempt));
                continue;
            }

            JsonNode body = parse(response.body());
            int status = response.statusCode();
            if (status >= 200 && status < 300) return body;

            String name = body.path("name").asText("unknown_error");
            boolean retryable = status >= 500
                || (status == 429 && !name.equals("monthly_quota_exceeded"))
                || name.equals("concurrent_idempotent_requests");
            if (!retryable || attempt == ATTEMPTS) {
                throw new CrescaException(status, name, body.path("message").asText(""));
            }
            long waitMillis = response.headers().firstValue("retry-after")
                .map(seconds -> Long.parseLong(seconds) * 1000)
                .orElse(backoff(attempt));
            Thread.sleep(waitMillis);
        }
    }

    private JsonNode parse(String body) {
        try {
            return json.readTree(body);
        } catch (IOException e) {
            return json.createObjectNode(); // a proxy error may have no JSON body
        }
    }

    // 1s, 2s, 4s... plus up to 250 ms of jitter.
    private static long backoff(int attempt) {
        return (1L << (attempt - 1)) * 1000 + ThreadLocalRandom.current().nextLong(250);
    }

    public static class CrescaException extends RuntimeException {
        public final int status;
        public final String name;

        CrescaException(int status, String name, String message) {
            super(status + " " + name + ": " + message);
            this.status = status;
            this.name = name;
        }
    }
}
```

`post` also declares `InterruptedException`, since `send` and `Thread.sleep` block. Let it propagate, or restore the interrupt flag if you catch it, so a shutdown can stop the retry loop.

Using it:

```java
CrescaClient cresca = new CrescaClient(System.getenv("CRESCA_API_KEY"));

JsonNode sent = cresca.post("/emails", Map.of(
    "from", "Acme <hello@acme.com>",
    "to", List.of(user.email()),
    "subject", "Welcome to Acme",
    "html", "<p>Hi " + HtmlUtils.htmlEscape(user.firstName()) + ", your account is ready.</p>"
), "welcome/" + user.id());

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

The shorter snippets leave out imports for `Map`, `List`, `Files`, `Path` and `Base64`. Escape user input before it lands in HTML: `HtmlUtils.htmlEscape` comes with Spring, and the OWASP Java Encoder or Apache Commons Text work elsewhere.

## Send a template with variables

Markup in Java strings gets old fast. Instead, build the email in Cresca's template editor, put triple-brace placeholders such as `{{{RESET_LINK}}}` where your data goes, and publish it. Your code then passes an alias and a map of values. Whatever is *published* is what renders, so you can work on a draft safely, and values are HTML-escaped. If a variable has no value and no fallback, the call fails with `422 validation_error` and the message names the variable. See [templates and variables](https://www.cresca.xyz/docs/templates).

```java
cresca.post("/emails", Map.of(
    "to", List.of(user.email()),
    "template", Map.of(
        "id", "password-reset", // the template's alias or id
        "variables", Map.of("NAME", user.firstName(), "RESET_LINK", resetUrl)
    )
), "password-reset/" + resetRequestId);
```

One JVM detail: `Map.of` throws `NullPointerException` on a null value, so a user without a first name fails before the request is even built. Default it first, for example with `Objects.requireNonNullElse`.

## Add attachments

The API wants file bytes as base64 strings inside the JSON, with a cap of 20 files and 7 MB per email. In Java that takes two calls: `Files.readAllBytes` and `Base64.getEncoder().encodeToString`. Use the basic encoder: `getMimeEncoder()` adds line breaks and `getUrlEncoder()` changes two characters of the alphabet. Besides `filename` and `content`, a map may set `content_type`, and `content_id` for an image the HTML shows via `<img src="cid:logo">`. Executables (.exe, .js) are rejected and URL attachments don't exist yet.

```java
byte[] pdf = Files.readAllBytes(Path.of("invoices/inv-2026-0042.pdf"));

cresca.post("/emails", Map.of(
    "from", "Acme Billing <billing@acme.com>",
    "to", List.of(customer.email()),
    "subject", "Your invoice INV-2026-0042",
    "html", "<p>Thanks for your payment. Your invoice is attached.</p>",
    "attachments", List.of(Map.of(
        "filename", "inv-2026-0042.pdf",
        "content", Base64.getEncoder().encodeToString(pdf),
        "content_type", "application/pdf"
    ))
), "invoice/inv-2026-0042");
```

## Send batches of 100 from a List

`POST /emails/batch` accepts a `List` of at most 100 maps. Any single-send field works except `attachments` and `scheduled_at`. Validation covers the whole list: if one entry is wrong, Cresca sends none, and the `CrescaException` message gives the entry's zero-based index. The `data` array that comes back keeps your order. Since the whole list is one request for rate-limit purposes, batching is how you reach thousands of emails a minute.

```java
List<Map<String, Object>> emails = users.stream()
    .map(u -> Map.<String, Object>of(
        "from", "Acme <hello@acme.com>",
        "to", List.of(u.email()),
        "subject", "Your weekly summary",
        "html", renderSummary(u)))
    .toList();

for (int i = 0; i < emails.size(); i += 100) {
    List<Map<String, Object>> chunk = emails.subList(i, Math.min(i + 100, emails.size()));
    JsonNode result = cresca.post("/emails/batch", chunk, "weekly-summary/2026-10-27/" + (i / 100));
    System.out.printf("Batch %d: %d emails accepted%n", i / 100, result.get("data").size());
}
```

The key holds the date and chunk number, so if the job dies halfway and reruns within 24 hours, chunks that already went out aren't sent twice.

Rate limits per plan, in requests per second: Free 2, Professional 10, Premium 20, Ultra 50, Enterprise 100. A thread pool sized past that only buys you more 429 retries. The `to`, `cc` and `bcc` lists of one email hold 50 addresses between them, and the monthly allowance is charged per recipient.

## Use it in Spring Boot

In Spring the client becomes a singleton bean. Put `cresca.api-key=${CRESCA_API_KEY}` in `application.properties` so the value comes from the environment, never from the file. Inject it where an email starts, and send off the request thread with `@Async` or a queue listener:

```java
@Configuration
class CrescaConfig {
    @Bean
    CrescaClient crescaClient(@Value("${cresca.api-key}") String apiKey) {
        return new CrescaClient(apiKey);
    }
}

@Service
class WelcomeEmailService {
    private final CrescaClient cresca;

    WelcomeEmailService(CrescaClient cresca) {
        this.cresca = cresca;
    }

    @Async
    public void send(User user) throws Exception {
        cresca.post("/emails", Map.of(
            "to", List.of(user.email()),
            "template", Map.of("id", "welcome", "variables", Map.of("NAME", user.firstName()))
        ), "welcome/" + user.id());
    }
}
```

`@Async` does nothing until a configuration class carries `@EnableAsync`, and it only applies through the Spring proxy, so calling `send` from the same class runs it synchronously. An exception from a `void` async method never reaches the caller; the `AsyncUncaughtExceptionHandler` just logs it. If a failed email needs another chance after four attempts, use a queue listener so the broker can redeliver.

## Jakarta Mail or an email API?

Jakarta Mail and Spring's `JavaMailSender` are mature and the right choice if you run your own SMTP server. An API replaces sessions, transports and SMTP passwords with one HTTP request, and idempotency keys make retries safe. Cresca has no SMTP relay yet, so Java code talks to it over HTTP.

## Errors to handle when you send email with Java

What `CrescaClient` does with the errors you are likely to hit. The [errors page](https://www.cresca.xyz/docs/errors) has the complete list.

| Status | name | Cause | In CrescaClient |
| --- | --- | --- | --- |
| 403 | `invalid_from_address` | From isn't an active sender on a verified domain. | Throws `CrescaException` at once. |
| 422 | `validation_error` | Bad field value, or a template variable without a value. | Throws at once. |
| 422 | `missing_required_field` | to, from or subject absent and no template providing it. | Throws at once. |
| 429 | `rate_limit_exceeded` | Over your plan's requests per second. | Sleeps for retry-after, then retries. |
| 429 | `monthly_quota_exceeded` | You've sent this month's allowance. | Throws, no retry. |
| 409 | `concurrent_idempotent_requests` | The same Idempotency-Key is still in progress. | Backs off, then retries. |
| 5xx | `application_error` | Something broke at Cresca. | Retries with backoff. |
| none | `IOException` | The connection failed or timed out. | Retries, then rethrows after the fourth attempt. |

Cresca drops suppressed addresses (prior hard bounces, complaints, unsubscribes) without an error. The request still succeeds, so nothing is thrown. See [suppression](https://www.cresca.xyz/docs/suppression).

## Did the email arrive?

`post` returning normally means accepted, not delivered. Open [Transactional](https://app.cresca.xyz/transactional) in the app for a per-email timeline, or fetch it by id with a full-access key (a sending key can't read logs):

```bash
curl https://api.cresca.xyz/api/v1/emails/4ef9a417-02e9-4d39-ad75-9611e0fcc33c \
  -H "Authorization: Bearer $CRESCA_API_KEY"
```

Read `last_event` from the JSON: `queued` becomes `sent`, and the final state is `delivered` or `bounced`. Definitions live in [email lifecycle](https://www.cresca.xyz/docs/email-lifecycle).

## Questions Java developers ask

### Does this work with Kotlin?

Yes. `CrescaClient` is plain Java, so Kotlin can call it as it is. You can also port it to Ktor's client or OkHttp; the endpoint, headers and retry rules don't change.

### Can I keep using JavaMailSender?

Only with an SMTP server behind it. Cresca doesn't offer an SMTP relay yet, so `JavaMailSender` can't point at Cresca. If your code calls its own email interface, back it with `CrescaClient` and callers stay the same.

### Is there an official Cresca SDK for Java?

No. Any HTTP client speaks to it, so `java.net.http`, OkHttp or Spring's `RestClient` all work. The client here is small enough to own outright.

## The same tutorial in other languages

[Node.js](https://www.cresca.xyz/blog/send-email-nodejs) · [Python](https://www.cresca.xyz/blog/send-email-python) · [PHP](https://www.cresca.xyz/blog/send-email-php) · [Go](https://www.cresca.xyz/blog/send-email-golang) · [Ruby](https://www.cresca.xyz/blog/send-email-ruby) · [C# and .NET](https://www.cresca.xyz/blog/send-email-csharp) · [Next.js](https://www.cresca.xyz/blog/send-email-nextjs) · [Laravel](https://www.cresca.xyz/blog/send-email-laravel) · [Django](https://www.cresca.xyz/blog/send-email-django) · [Ruby on Rails](https://www.cresca.xyz/blog/send-email-rails)

Fields not covered here (cc, bcc, scheduling and more) are in the [send email API guide](https://www.cresca.xyz/blog/send-email-api). For background, the [transactional email API overview](https://www.cresca.xyz/blog/transactional-email-api) shows how the pieces fit, and [SMTP vs API](https://www.cresca.xyz/blog/smtp-vs-api-sending) helps if your team is still choosing between Jakarta Mail and HTTP.

## Send your first email from Java

Once a domain is verified and you have a sending key, the single-file example works unchanged. **[Create a Cresca account](https://app.cresca.xyz/signup)**. It's free for 30 days: 250 contacts, 1,000 emails and 20 AI emails, no credit card. API email and campaigns draw on one allowance. After signing up, the [quickstart](https://www.cresca.xyz/docs/quickstart) gets you to a first send, and the [API docs](https://www.cresca.xyz/docs) hold the reference.
