How to Send Email from Java: A Plain Java Program, Spring Boot, HTML, Attachments and Replies

Send email from Java over an API: a complete Java program to send email, then a Spring Boot endpoint, HTML, attachments and replies read in the same inbox.

By · · 15 min read

shell code from this guide, in a terminal, sending or reading email with Mailcycle

If you need to send email from Java, the usual answer is Jakarta Mail (formerly JavaMail) or Spring’s JavaMailSender, pointed at an SMTP server. That works, but it means finding an SMTP relay, managing its credentials, choosing between port 587 and 465, getting STARTTLS right, and building MIME messages by hand. And when the recipient replies, the answer lands in a mailbox your Java code still can’t see.

This tutorial takes the other route: a Java email API. You’ll add the Mailcycle Java SDK with Maven or Gradle, send a plain-text email from a main method, then send from a Spring Boot @RestController, with HTML, attachments and inline images. Then you’ll do what send-only APIs can’t: wait for the reply in the same inbox, read it, and answer in the same thread. Every Java snippet here compiles against the SDK, version 0.5.1.

It’s one post in our series on how to send email from any language. If you also work in other stacks, there are versions for Python, C# and Go.

To read mail as well as send it, see How to read email in Java: a complete program that reads an inbox, then attachments, waiting for a message and a Spring Boot webhook. The Java SDK page has the install lines and every call on one page.

Quick answer: how to send email in Java

To send email in Java without SMTP, add email.mailcycle:mailcycle from Maven Central, create a client with your API key, and call messages().send() with a from address on your account, one recipient, a subject and a body. The SDK makes a single HTTPS request and returns the Message-ID the email went out with. The complete program is next.

Java program to send email (plain Java, no Spring)

This is the whole program: one class, one main method, no framework. It reads the API key and the from address from environment variables, sends one email to the address you pass as an argument, and prints what came back.

import email.mailcycle.Mailcycle;
import email.mailcycle.Options;
import email.mailcycle.Outgoing;
import email.mailcycle.SendResult;

public class SendEmail {
    public static void main(String[] args) {
        String apiKey = System.getenv("MAILCYCLE_API_KEY"); // mak_..., from the API page in the app
        String from = System.getenv("MAILCYCLE_FROM");      // an address on your account
        String to = args.length > 0 ? args[0] : "you@example.com";

        Mailcycle mc = Mailcycle.withApiKey(apiKey, null, Options.defaults());

        SendResult sent = mc.messages().send(
                new Outgoing(from, to, "Hello from Java", """
                        Hi,

                        This email was sent from a plain Java program with the Mailcycle SDK.
                        """)
                        .fromName("Acme Notifications"));

        System.out.println("Message-ID: " + sent.messageId());
        System.out.println("Sent copy:  " + sent.sentCopyId());
    }
}

We compiled it with javac --release 17 against SDK 0.5.1 from Maven Central and ran it. It printed:

Message-ID: <1j4L7PdWCO8b8c7acIpXZwbWF2Z11Zu90yHb@letterhold.com>
Sent copy:  msg_pTUOzoL8qC9T

and the email arrived seconds later, which the ReadEmail program in the Java read email guide then printed from the recipient’s inbox. Steps 1 to 3 below get you the key, the library and the commands to run this Java code yourself, and the Spring Boot section after them puts the same call behind a REST endpoint.

What you’ll build

By the end you’ll have:

  • a plain Java program that sends a plain-text email, run with javac or your build tool;
  • a Spring Boot service with a POST /api/welcome endpoint that sends a welcome email, and a @RestControllerAdvice that maps mail errors to sensible HTTP statuses;
  • a mailer class that sends an HTML receipt and a PDF invoice with an inline logo;
  • a program that sends an email, waits for the reply, reads it and answers it in the same thread.

All of it sends from addresses you own on Mailcycle: transactional mail, notifications, sign-in and verification emails, and replies from your app or your agent. Mailcycle is built for mail you send from your own addresses and the replies that come back.

Flow: your Java code calls the Java SDK, Mailcycle sends the email from your address, and the recipient gets it
Your Java code calls the Java SDK, and Mailcycle sends the email from your address.

Prerequisites

  • Java 17 or later. Check with java -version. The SDK’s only dependency is Jackson, for JSON; the HTTP client, WebSocket client and cryptography all come from the JDK.
  • Maven or Gradle. Both are shown below.
  • Spring Boot 3 if you want to follow the framework section. Spring Boot 3 also needs Java 17, so the two line up.
  • A Mailcycle account on the Scale plan, or the free 7-day Scale trial. Sending with an API key is a Scale feature. The trial needs no card, and nothing is charged when it ends.
  • An email account you can read, such as Gmail or Outlook, to receive your test messages.

Step 1: Create an account, an address and an API key

  1. Open app.mailcycle.email/operator/signup and create an account. There’s no email or password: the account is a 12-word recovery phrase made on your device. Save it somewhere safe, because it’s the only way back in.
  2. In the sidebar, open Plans & Billing and choose Start free trial to switch on Scale for 7 days.
  3. Open Email addresses and create the address you’ll send from, such as receipts-x7k2@ on one of Mailcycle’s shared domains. On Scale you can also use your own domain.
  4. Open API, then the Keys tab. Name the key, choose Create key, and copy the token. It starts with mak_ and is shown only once.

Keep the key out of your source code. Put it, and the address you’ll send from, in environment variables:

export MAILCYCLE_API_KEY="mak_..."
export MAILCYCLE_FROM="receipts-x7k2@example-pool.email"

On a server, set these through your platform’s secret store, a Kubernetes secret, or whatever your deployment already uses for database passwords. The Authentication guide lists what a key can and can’t do, and API keys covers revoking them.

Step 2: Add the Java email library with Maven or Gradle

The SDK is published to Maven Central as email.mailcycle:mailcycle.

With Maven, add this to the <dependencies> in your pom.xml:

<dependency>
  <groupId>email.mailcycle</groupId>
  <artifactId>mailcycle</artifactId>
  <version>0.5.1</version>
</dependency>

With Gradle and the Kotlin DSL, in build.gradle.kts:

dependencies {
    implementation("email.mailcycle:mailcycle:0.5.1")
}

Or with the Groovy DSL, in build.gradle:

dependencies {
    implementation 'email.mailcycle:mailcycle:0.5.1'
}

Everything you need is in the email.mailcycle package. Because it’s an ordinary JVM library, the same dependency works from Kotlin and Scala.

Step 3: Compile and run the Java program

With Maven or Gradle, put SendEmail.java under src/main/java and run the class from your IDE, or with Maven’s exec plugin: mvn compile exec:java -Dexec.mainClass=SendEmail -Dexec.args=you@example.com.

With no build tool at all, plain javac works. Put four jars in a lib folder: mailcycle-0.5.1.jar and the jackson-databind, jackson-core and jackson-annotations jars it depends on, all from Maven Central. Then:

export MAILCYCLE_API_KEY="mak_..."
export MAILCYCLE_FROM="receipts-x7k2@example-pool.email"
javac -cp 'lib/*' SendEmail.java
java -cp 'lib/*:.' SendEmail you@example.com

On Windows, the class path separator is ;, so the last line is java -cp "lib/*;." SendEmail you@example.com. Change you@example.com to an inbox you can check, run it, and the email arrives with “Acme Notifications” on the From line.

What’s going on:

  • Mailcycle.withApiKey(key, phrase, options) builds the client. The second argument is the recovery phrase, and null is fine for a client that only sends. Options.defaults() points at the live API with a 30-second timeout; .withTimeout(Duration) changes the timeout.
  • new Outgoing(from, to, subject, text) is the message. All four are required. from must be an address on your account, and to takes one recipient. To send the same notice to three people, make three calls, so each person gets their own copy and their own thread.
  • .fromName("Acme Notifications") sets the display name on the From line. It’s optional.
  • send() returns a SendResult. messageId() is the Message-ID header the mail went out with, worth logging so you can match it up later. sentCopyId() is the id of the copy kept in the address’s Sent folder.

That copy matters. Every email you send is filed in the address’s Sent folder, encrypted to the address’s key like received mail, and marked as sent through the API. Your app’s outgoing mail has a record without you building one.

Each send counts against your plan’s daily sending limit, which is worth knowing before you put a send inside a loop.

How to send email from Spring Boot (without JavaMailSender)

In a Spring Boot application, make the client a singleton @Bean. The SDK’s client is safe to share between threads, so one instance serves every request, and Spring injects it wherever you need it.

First, the configuration. In application.properties, map the environment variables to properties:

mailcycle.api-key=${MAILCYCLE_API_KEY}
mailcycle.from=${MAILCYCLE_FROM}

Then a @Configuration class that builds the client:

package com.example.mail;

import email.mailcycle.Mailcycle;
import email.mailcycle.Options;
import java.time.Duration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MailcycleConfig {

    @Bean
    public Mailcycle mailcycle(@Value("${mailcycle.api-key}") String apiKey) {
        // One client for the whole application. It is safe to share between threads.
        return Mailcycle.withApiKey(apiKey, null, Options.defaults().withTimeout(Duration.ofSeconds(15)));
    }
}

A shorter timeout than the default suits a web request: if the API is slow to answer, you’d rather fail the request and say so than hold a thread for 30 seconds.

Now the @RestController. It takes a JSON body with an email address and a name, sends a welcome email, and returns the Message-ID:

package com.example.mail;

import email.mailcycle.Mailcycle;
import email.mailcycle.Outgoing;
import email.mailcycle.SendResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class WelcomeController {

    private final Mailcycle mailcycle;
    private final String from;

    public WelcomeController(Mailcycle mailcycle, @Value("${mailcycle.from}") String from) {
        this.mailcycle = mailcycle;
        this.from = from;
    }

    public record WelcomeRequest(String email, String name) {}

    public record WelcomeResponse(String messageId) {}

    @PostMapping("/welcome")
    public ResponseEntity<WelcomeResponse> welcome(@RequestBody WelcomeRequest request) {
        String text = """
                Hi %s,

                Thanks for signing up. Reply to this email if you have any questions:
                it comes straight back to us.
                """.formatted(request.name());

        SendResult sent = mailcycle.messages().send(
                new Outgoing(from, request.email(), "Welcome to Acme", text)
                        .fromName("Acme"));

        return ResponseEntity.ok(new WelcomeResponse(sent.messageId()));
    }
}

Start the application and try it:

curl -X POST http://localhost:8080/api/welcome \
  -H "Content-Type: application/json" \
  -d '{"email": "you@example.com", "name": "Sam"}'

You’ll get back {"messageId":"<...>"} and the email in your inbox. “Reply to this email” in that template isn’t a figure of speech: the reply goes to the address you sent from, and later in this guide your code reads it.

In a real service you’d validate request.email() and decide what to do if the send fails. The cleanest place for the second part is a @RestControllerAdvice, which you’ll write in the error-handling section below, so the controller can stay this short.

Sending email asynchronously in Spring Boot

The SDK’s calls are blocking. That’s usually what you want, because the caller learns at once whether the email went. When sending shouldn’t hold up the response, run it on an executor of your own:

import email.mailcycle.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AsyncSend {
    static void run(Mailcycle mc, Outgoing outgoing) {
        ExecutorService mailPool = Executors.newFixedThreadPool(4);

        CompletableFuture<SendResult> pending =
                CompletableFuture.supplyAsync(() -> mc.messages().send(outgoing), mailPool);

        pending
                .thenAccept(sent -> System.out.println("Sent " + sent.messageId()))
                .exceptionally(error -> {
                    System.err.println("Send failed: " + error.getCause().getMessage());
                    return null;
                });
    }
}

In a real application, create the pool once (as a bean, for instance) rather than per call, and log failures somewhere you’ll see them. On Java 21 and later, Executors.newVirtualThreadPerTaskExecutor() is a good fit for this kind of I/O-bound work, and Spring Boot 3.2 and later can run request handling on virtual threads with spring.threads.virtual.enabled=true, which makes the blocking call cheap without any change to the controller.

How to send HTML email in Java

An HTML email should always carry a plain-text part too, for mail clients that don’t show HTML and for readers who prefer text. The SDK makes this the default shape: the constructor’s fourth argument is the text, and .html(...) adds the HTML alongside it.

Here’s a receipt, using a Java text block for the markup:

public SendResult sendReceipt(String to, String orderId, String total) {
    String text = "Thanks for your order " + orderId + ".\nTotal: " + total + "\n";
    String html = """
            <!doctype html>
            <html>
              <body style="font-family: system-ui, sans-serif; line-height: 1.5">
                <h1 style="font-size: 20px">Thanks for your order</h1>
                <p>Order <strong>%s</strong> is confirmed.</p>
                <p>Total: <strong>%s</strong></p>
              </body>
            </html>
            """.formatted(orderId, total);

    return mailcycle.messages().send(
            new Outgoing(from, to, "Your receipt for order " + orderId, text)
                    .html(html));
}

Two tips that apply to HTML email whatever sends it. Keep styles inline, as above, because many mail clients ignore <style> blocks. And if any part of the HTML comes from user input, escape it before you put it in the template. In a Spring Boot app you can render the HTML with Thymeleaf or any other template engine and pass the resulting string to .html(); the SDK doesn’t mind where the string came from.

How to send email with an attachment in Java

Attachments are raw bytes. Read the file, wrap it in an OutgoingAttachment with a file name and a MIME type, and the SDK base64-encodes it for you.

The same mechanism does inline images. Give an attachment a contentId, and the HTML can show it with cid: and that id, so your logo appears in the email without loading anything from a remote server:

public SendResult sendInvoice(String to, Path invoicePdf, Path logoPng) throws IOException {
    byte[] pdf = Files.readAllBytes(invoicePdf);
    byte[] logo = Files.readAllBytes(logoPng);

    Outgoing outgoing = new Outgoing(from, to, "Your invoice", "Your invoice is attached as a PDF.")
            .html("""
                    <img src="cid:logo" alt="Acme" width="120">
                    <p>Your invoice is attached as a PDF.</p>
                    """)
            .attachments(List.of(
                    new OutgoingAttachment("invoice.pdf", pdf).mimeType("application/pdf"),
                    new OutgoingAttachment("logo.png", logo).mimeType("image/png").contentId("logo")));

    return mailcycle.messages().send(outgoing);
}

The imports for these two methods are java.io.IOException, java.nio.file.Files, java.nio.file.Path, java.util.List and email.mailcycle.*. If the PDF is generated in memory, by a library such as OpenPDF or iText, skip Files and pass its byte[] straight in. Without a mimeType an attachment goes as application/octet-stream, so set it when you know it.

A message can carry up to ten files, 3.5 MB between them, and program and script files such as .exe and .js are refused. The SDK checks the count and the size before sending, so an oversized message fails fast with an ApiException and nothing goes out. The Sent copy keeps the attachments, encrypted like everything else in it.

Reply in the same thread with inReplyTo

Mail clients group messages into conversations using the In-Reply-To and References headers, which point at the Message-ID of the email being answered. With Jakarta Mail you set those headers yourself. With the SDK you pass the message you’re answering to .replyTo(...), and it fills in the threading for you:

mc.messages().send(new Outgoing(from, original.replyTo(), "Re: " + original.subject(), "Thanks, we're on it.")
        .replyTo(original));

original is a Message you’ve read, as in the next section. original.replyTo() is the address the sender asked replies to go to, which falls back to their From address when they didn’t set one. Behind the scenes .replyTo(original) sends two fields with the request: inReplyTo, the Mailcycle id of the original message, and inReplyToHeader, its Message-ID, which threads the reply in the recipient’s mail client. You still choose the subject; keeping Re: and the original subject helps clients that thread by subject too.

How to receive and read email replies in Java

This is where an API that receives mail as well as sending it pays off. The welcome email said “reply to this email”. When someone does, the reply lands in the address you sent from, and the same SDK reads it.

Reading needs your recovery phrase. Mail is encrypted the moment it arrives, with keys from the phrase, and the SDK derives those keys on your machine. Add it as an environment variable alongside the key, and treat it with at least the care you give the key, since it opens all of the account’s mail:

export MAILCYCLE_PHRASE="twelve words ..."

Wait for the reply to an email you sent

This program sends an email, waits up to ten minutes for the reply, prints it, and answers it in the same thread:

import email.mailcycle.*;
import java.time.Duration;
import java.time.Instant;

public class ReplyAndWait {
    public static void main(String[] args) {
        Mailcycle mc = Mailcycle.withApiKey(
                System.getenv("MAILCYCLE_API_KEY"),
                System.getenv("MAILCYCLE_PHRASE"),   // needed to open mail
                Options.defaults());

        String from = System.getenv("MAILCYCLE_FROM");
        Address address = mc.addresses().list().stream()
                .filter(a -> a.emailAddress().equalsIgnoreCase(from))
                .findFirst()
                .orElseThrow(() -> new IllegalStateException(from + " is not on this account"));

        // Take the time before sending, so a fast reply still counts.
        Instant beforeSend = Instant.now();
        mc.messages().send(new Outgoing(from, "customer@example.com",
                "Your order has shipped", "Reply to this email if anything looks wrong."));

        Message reply = mc.messages().waitFor(new WaitFor()
                .addressId(address.id())
                .from("customer@example.com")
                .since(beforeSend)
                .timeout(Duration.ofMinutes(10)));

        System.out.println(reply.fromAddress() + ": " + reply.subject());
        System.out.println(reply.text());

        // Answer in the same thread.
        String subject = reply.subject().regionMatches(true, 0, "Re:", 0, 3)
                ? reply.subject()
                : "Re: " + reply.subject();
        mc.messages().send(new Outgoing(from, reply.replyTo(), subject, "Thanks, we're on it.")
                .replyTo(reply));
    }
}

A few details:

  • mc.addresses().list() returns the account’s addresses. You need the address’s id, like ibx_…, for waitFor, and the email address string isn’t the id, so look it up once and keep it.
  • waitFor listens on the account’s event stream and returns the next matching message, already decrypted. If the stream can’t be opened it checks the address every five seconds instead, which is why addressId is worth passing.
  • since(beforeSend) matters. By default waitFor counts mail from the moment it’s called, so a reply that arrives while your code is still finishing the send could be missed. Taking the time before the send closes that gap, with five seconds allowed for clock differences.
  • from and subject filter on part of the sender or subject, case-insensitively. With no filters, any new message matches.
  • No match in time throws an ApiException whose code() is timeout, so a test or a job fails with a reason instead of hanging.

This pattern is the core of email-driven workflows: a support address your service answers, an order confirmation that customers can reply to, or an end-to-end test that signs up on your staging site and waits for the verification email. It’s also how an AI agent works with email; if that’s your use case, see how to give Claude Code its own email address over MCP and the AI agents guide.

Read the inbox

To go through what’s arrived rather than wait for one message, list a page of the inbox:

MessagePage page = mc.messages().list(address.id(), null, 20, null);
for (Message message : page.messages()) {
    if (!message.opened()) {
        continue;   // no phrase, or the wrong one
    }
    System.out.println(message.receivedAt() + "  " + message.fromAddress() + "  " + message.subject());

    String body = message.safeHtml().isEmpty() ? message.text() : message.safeHtml();

    for (Attachment file : message.attachments()) {
        if (!file.stored()) {
            continue;
        }
        byte[] data = mc.messages().attachment(message, file.index());
        System.out.println("  " + file.filename() + " (" + file.mimeType() + ", " + data.length + " bytes)");
    }
}

The arguments to list are the address id, the folder (null for the inbox, or "sent", "junk", "trash", "starred"), how many to fetch, and a cursor; pass page.nextCursor() back to get the next page, or call mc.messages().all(address.id(), null) to walk every page. Messages come back parsed: sender, subject, text, HTML and attachments, with no multipart MIME for you to walk.

Two things to know. A message that can’t be opened comes back with opened() false and empty content rather than throwing, so one bad message doesn’t break the page. And html() is the HTML exactly as the sender wrote it, remote images and all, while safeHtml() has every remote image, stylesheet and embed removed; render safeHtml() if you show mail to anyone. The Reading mail guide covers folders, stars and read state.

For a server that should react to incoming mail without holding a connection open, webhooks post each new-message event to your URL, and WebhookSignature.verifyNow(...) checks it came from Mailcycle. The Java SDK page has a Spring Boot webhook endpoint ready to copy.

Handle errors in Java by error code

Everything the SDK throws extends MailcycleException, which is unchecked, so there are no throws clauses to thread through your code. A failed API call is an ApiException with three things on it: status(), the HTTP status (0 if the request never got an answer); code(), a stable machine-readable code; and apiMessage(), a human-readable explanation. Match on code(), never on the message text.

The codes you’re most likely to meet when sending:

Code Status What it means
plan_required 403 Sending with an API key needs Scale or above.
not_your_address 403 The from address isn’t on this account.
invalid_address 400 The to address isn’t valid.
address_paused 403 The from address is paused, for example after a missed payment.
domain_not_sending 409 Sending isn’t on yet for a domain you brought; it usually follows receiving within minutes.
too_many_attachments, attachment_blocked 400 More than ten files, or a program or script file. The SDK catches too many files before sending, with status 0.
attachments_too_large, message_too_large 413 The files or the whole message are too big. Oversized files are caught by the SDK first, with status 0.
rate_limited 429 Too many requests; the message says how long to wait.
daily_send_limit 429 Today’s sending is used up. It resumes at 00:00 UTC.
network_error 0 The request didn’t reach the API, or the answer didn’t come back.
send_failed and other 5xx 5xx A temporary failure. Retry with backoff.

The full list is on the Errors reference, and the numbers behind rate_limited and daily_send_limit are in Rate limits.

A sensible pattern is to retry only what’s worth retrying, a few times with backoff, and to report everything else clearly:

import email.mailcycle.*;

public class Errors {
    static SendResult sendWithRetry(Mailcycle mc, Outgoing outgoing) throws InterruptedException {
        long delayMillis = 2_000;
        for (int attempt = 1; ; attempt++) {
            try {
                return mc.messages().send(outgoing);
            } catch (ApiException e) {
                boolean worthRetrying = e.code().equals("rate_limited")
                        || (e.status() >= 500 && !e.code().equals("sending_paused"));
                if (!worthRetrying || attempt == 4) {
                    throw e;
                }
                Thread.sleep(delayMillis);
                delayMillis *= 2;
            }
        }
    }

    static void handle(Mailcycle mc, Outgoing outgoing) throws InterruptedException {
        try {
            SendResult sent = sendWithRetry(mc, outgoing);
            System.out.println("Sent " + sent.messageId());
        } catch (ApiException e) {
            switch (e.code()) {
                case "plan_required" -> System.err.println("Sending with an API key needs Scale or above.");
                case "not_your_address" -> System.err.println("The from address is not on this account.");
                case "invalid_address" -> System.err.println("The recipient address is not valid.");
                case "daily_send_limit" -> System.err.println("Today's sending is used up; it resets at 00:00 UTC.");
                case "network_error" -> System.err.println("Could not reach Mailcycle: " + e.apiMessage());
                default -> System.err.println("Send failed: " + e.status() + " " + e.code() + " " + e.apiMessage());
            }
        } catch (MailcycleException e) {
            System.err.println("Mailcycle error: " + e.getMessage());
        }
    }
}

daily_send_limit and sending_paused aren’t retried because they last until midnight UTC; retrying in a loop only burns requests. network_error isn’t retried automatically either, on purpose: if the connection dropped after the request left, the email may already have gone, and a blind retry could send it twice. Where a duplicate is harmless, such as a sign-in code, add it to the retry list.

In Spring Boot, map the same codes to HTTP statuses once, in a @RestControllerAdvice, and every controller that sends mail gets consistent error responses:

package com.example.mail;

import email.mailcycle.ApiException;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class MailErrors {

    @ExceptionHandler(ApiException.class)
    public ResponseEntity<Map<String, String>> onMailError(ApiException e) {
        HttpStatus status = switch (e.code()) {
            // The caller's input.
            case "invalid_address", "invalid_field" -> HttpStatus.BAD_REQUEST;
            case "attachments_too_large", "message_too_large" -> HttpStatus.PAYLOAD_TOO_LARGE;
            // Slow down, or try again tomorrow.
            case "rate_limited", "daily_send_limit" -> HttpStatus.TOO_MANY_REQUESTS;
            // Our configuration: the wrong from address, the wrong plan, a paused address.
            case "not_your_address", "plan_required", "address_paused", "domain_not_sending" ->
                    HttpStatus.SERVICE_UNAVAILABLE;
            default -> HttpStatus.BAD_GATEWAY;
        };
        return ResponseEntity.status(status).body(Map.of("error", e.code(), "message", e.apiMessage()));
    }
}

The split is deliberate: a bad recipient is the caller’s problem (400), while a from address that isn’t yours or a plan without API sending is a problem with your own deployment, so the caller gets a 503 and you get something to fix.

The same email with cURL: what the SDK sends

Under the hood, send() is one HTTPS request with a JSON body and a bearer token. Here is the equivalent call with cURL, which is handy for checking a key from the terminal or calling the API from a language without an SDK:

curl https://api.mailcycle.email/messages/send \
  -H "Authorization: Bearer $MAILCYCLE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "from": "receipts-x7k2@example-pool.email",
    "to": "someone@example.com",
    "subject": "Hello",
    "text": "Plain text body",
    "html": "<p>Plain text body</p>",
    "fromName": "Acme Notifications"
  }'
{ "sent": true, "messageId": "<…>", "sentCopyId": "msg_…" }

The Java builder maps one to one onto these fields: .html() to html, .fromName() to fromName, .replyTo(message) to inReplyTo and inReplyToHeader, and each OutgoingAttachment to an object with filename, mimeType, contentId and base64 content. What the SDK adds is everything around the request: encoding attachments, checking their size before anything is sent, typed results and errors, and, for reading, decrypting mail on your machine, which you’d otherwise have to implement yourself. The Sending mail guide documents every field.

Jakarta Mail and JavaMailSender vs an email API

Jakarta Mail is the standard Java mail library, and Spring Boot’s JavaMailSender (from spring-boot-starter-mail) wraps it. Both are mature and capable. What they need is an SMTP server to talk to, and settings for it. A typical Spring Boot setup looks like this:

spring.mail.host=smtp.example.com
spring.mail.port=587
spring.mail.username=${SMTP_USERNAME}
spring.mail.password=${SMTP_PASSWORD}
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

From there you build a MimeMessage, usually through MimeMessageHelper in multipart mode for HTML and attachments, and send it. Receiving is a separate job: Jakarta Mail can read mail over IMAP, but that’s another server, another set of credentials and a polling loop of your own.

Here’s how the two approaches compare for the jobs in this tutorial:

Jakarta Mail / JavaMailSender over SMTP Mailcycle Java SDK
What you need An SMTP server or relay, a username and password or app password An API key, and an address on your account
Network setup SMTP host and port (587 with STARTTLS or 465 with implicit TLS); some hosting providers restrict outbound SMTP ports HTTPS to api.mailcycle.email on port 443
Dependencies jakarta.mail plus an implementation such as Eclipse Angus Mail, or spring-boot-starter-mail One library; Jackson is its only dependency
HTML with a text part Multipart MIME, usually via MimeMessageHelper .html() alongside the required text
Attachments and inline images MimeBodyPart or addAttachment / addInline OutgoingAttachment, with .contentId() for inline
Threading a reply Set In-Reply-To and References headers yourself .replyTo(message) threads it for you
Receiving replies A separate IMAP mailbox, its credentials and your own polling The same address, with waitFor, list and webhooks
A record of what was sent Depends on your SMTP provider A copy in the address’s Sent folder, stored encrypted
Errors MessagingException and SMTP reply codes ApiException with stable codes such as invalid_address

An email API suits Java apps that would rather not operate mail infrastructure, and especially apps that need to read the replies to what they send: the same client, the same address and the same API key cover both.

Using it from Kotlin

The SDK is a plain JVM library, so Kotlin calls it directly. The builder methods chain the same way:

import email.mailcycle.*

val mc = Mailcycle.withApiKey(System.getenv("MAILCYCLE_API_KEY"), null, Options.defaults())

mc.messages().send(
    Outgoing(System.getenv("MAILCYCLE_FROM"), "you@example.com", "Hello from Kotlin", "Sent from the JVM.")
        .fromName("Acme")
)

Next steps

You can now send email from Java with plain text, HTML, attachments and inline images, from a command-line program or a Spring Boot endpoint, and read and answer the replies in the same inbox. From here:

FAQ

What is a simple Java program to send email?

A single class with a main method is enough: build a client with Mailcycle.withApiKey(apiKey, null, Options.defaults()), then call mc.messages().send(new Outgoing(from, to, subject, text)) and print the SendResult. The complete SendEmail program near the top of this guide reads the key and the from address from environment variables and needs no Spring or SMTP settings.

How do I run Java code to send email without Maven or Gradle?

Put mailcycle-0.5.1.jar and its three Jackson jars from Maven Central in a lib folder, then run javac -cp 'lib/*' SendEmail.java and java -cp 'lib/*:.' SendEmail you@example.com. On Windows, use ; instead of : in the class path.

Which Java API can I use to send email?

Jakarta Mail (formerly JavaMail) sends through an SMTP server you configure. An email API such as Mailcycle sends with one HTTPS call from the email.mailcycle:mailcycle library, and the same client reads the replies. Mailcycle's Java SDK is Apache-2.0 licensed and needs Java 17 or later.

How do I send an email in Java without SMTP?

Add email.mailcycle:mailcycle from Maven Central, build a client with Mailcycle.withApiKey(apiKey, null, Options.defaults()), and call mc.messages().send(new Outgoing(from, to, subject, text)). It is one HTTPS request, so there is no SMTP host, port or TLS mode to configure. The from address must be one on your Mailcycle account.

Is JavaMail the same as Jakarta Mail?

Yes. JavaMail was renamed Jakarta Mail when Java EE moved to the Eclipse Foundation, and from version 2.0 its packages moved from javax.mail to jakarta.mail. Spring Boot 3's JavaMailSender uses Jakarta Mail underneath. Both talk to an SMTP server you supply.

How do I send email from a Spring Boot REST API?

Register one Mailcycle client as a @Bean, inject it into a @RestController, and call messages().send() inside a @PostMapping handler. The client is safe to share between threads, so one instance serves every request. A @RestControllerAdvice can turn the SDK's ApiException codes into HTTP statuses.

How do I send an HTML email in Java?

Call .html(...) on the Outgoing as well as giving it a plain-text body in the constructor. The message goes out with both parts, and mail clients that cannot show HTML fall back to the text. To show an image inline, attach it with a contentId and refer to it as cid: plus that id.

How do I send an email with an attachment in Java?

Read the file into a byte[] and pass it as new OutgoingAttachment("invoice.pdf", bytes).mimeType("application/pdf") in .attachments(List.of(...)). The SDK base64-encodes it for you. A message can carry up to ten files, 3.5 MB between them, and program or script files such as .exe and .js are refused.

Can I receive and read email replies in Java too?

Yes. Replies land in the same Mailcycle address you sent from. Build the client with your recovery phrase as well as the key, then mc.messages().waitFor(...) returns the next matching message decrypted, or mc.messages().list(...) pages through the inbox. See Reading mail.

Is the Mailcycle Java client asynchronous?

Its calls are blocking, built on the JDK's java.net.http.HttpClient, and one client is safe to use from many threads. To send without holding up a request thread, wrap the call in CompletableFuture.supplyAsync with your own executor, or run it on virtual threads on Java 21 and later.

Does the Java SDK work with Kotlin?

Yes. It is a plain JVM library, so a Kotlin project adds it with the same Gradle line, implementation("email.mailcycle:mailcycle:0.5.1"), and calls it like any other Java API. It needs Java 17 or later.

Which Mailcycle plan do I need to send email with an API key?

Sending with an API key needs the Scale plan or above. You can try it with the free 7-day Scale trial, which needs no card. See pricing.

Can I send from my own domain?

Yes. On Scale you can bring your own domains and create addresses on them, so mail goes out from an address like orders@yourcompany.com. Setup is a TXT record and a nameserver change; see Your own domains.

Send email from any language