Guide · Go, Rust & JVM
How to send email with Java
Send email from Java 11+ with the built-in HttpClient and the Stack Emails API.
Last reviewed November 2026
1. Set up
You need a Stack Emails API key (create one free) and a verified sending domain.
export STACKEMAILS_API_KEY=se_live_xxxxxxxxxxxx
2. Send your first email
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class SendEmail {
public static void main(String[] args) throws Exception {
String json = """
{
"from": "Acme <hello@mail.acme.com>",
"to": "ada@example.com",
"subject": "Welcome to Acme",
"html": "<p>Thanks for signing up!</p>"
}
""";
HttpRequest req = HttpRequest.newBuilder(URI.create("https://stackemails.com/v1/emails"))
.header("Authorization", "Bearer " + System.getenv("STACKEMAILS_API_KEY"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> res = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(res.statusCode() + " " + res.body());
}
}
A successful request returns 202 with the message id, for example { "id": "msg_5b1f0c6c2a8e4e0f", "status": "queued" }. Errors return a JSON body with error.code and error.message (see errors).
Text blocks (""") need Java 15+. On Java 11, build the JSON string normally or use Jackson.
Production checklist
- Keep the API key in an environment variable or secret manager, never in client-side code.
- Add an
Idempotency-Keyheader to retries so a timeout never sends twice (idempotency). - Subscribe to webhooks for bounces and complaints.
- Check your domain's SPF, DKIM and DMARC records.
- Start from a tested email template for password resets, receipts and invites.