Frameworks

How to send email in Java

Short answer

To send email in Java, either call an email API with the HttpClient built into the JDK since Java 11, or use Jakarta Mail (the successor to JavaMail) with the Eclipse Angus implementation to send over SMTP. The API route needs no extra library and returns an id you can track. Jakarta Mail is the standard choice when you must speak SMTP. Verify your domain with SPF, DKIM and DMARC before you send.

Last checked 16 November 2026

Java gives you two good ways to send email: POST JSON to an email API with the HttpClient that ships with the JDK, or use Jakarta Mail to talk SMTP. The API route needs no dependencies and suits web apps and workers. Jakarta Mail is the right tool when a system only accepts SMTP. If you use Spring Boot, see our Spring Boot email guide, which wraps both.

Option 1: java.net.http.HttpClient and an email API

java.net.http.HttpClient has been part of the JDK since Java 11. The example below uses Java 17 features (text blocks and formatted), so it runs on any current LTS release. It sends through Mailcandor; other email APIs look much the same.

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 {
    private static final HttpClient CLIENT = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();

    public static void main(String[] args) throws Exception {
        String json = """
            {
              "from": "Acme <hello@acme.com>",
              "to": "sam@example.com",
              "subject": "Your login code",
              "html": "<p>Your code is <b>481 203</b></p>",
              "text": "Your code is 481 203"
            }
            """;

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.mailcandor.com/v1/emails"))
                .timeout(Duration.ofSeconds(30))
                .header("Authorization", "Bearer " + System.getenv("MAILCANDOR_KEY"))
                .header("Content-Type", "application/json")
                .header("Idempotency-Key", "signup-4821-welcome")
                .POST(HttpRequest.BodyPublishers.ofString(json))
                .build();

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

        if (response.statusCode() != 202) {
            throw new IllegalStateException(
                "Send failed (" + response.statusCode() + "): " + response.body());
        }
        System.out.println(response.body()); // {"id":"...","status":"queued"}
    }
}

The text block keeps the example free of dependencies, but do not build JSON from user input by string concatenation: a quote in a name breaks the body. In a real app, serialize a record or Map with Jackson, Gson or jakarta.json, then pass the string to BodyPublishers.ofString.

Three points worth knowing:

  • Create one HttpClient and reuse it. It is thread safe and pools connections.
  • Idempotency-Key lets you retry after a timeout without sending twice. Use a value that identifies the email, such as order-1042-receipt.
  • 202 means queued. Delivery, bounces and complaints come later as webhooks, keyed by the id in the response.

For async code, CLIENT.sendAsync(request, BodyHandlers.ofString()) returns a CompletableFuture. On Java 21 and later, virtual threads make the blocking send cheap as well.

Attachments through the API

Attachments go in the JSON as base64. java.util.Base64 handles the encoding:

byte[] pdf = java.nio.file.Files.readAllBytes(java.nio.file.Path.of("invoice-1042.pdf"));
String content = java.util.Base64.getEncoder().encodeToString(pdf);
// add to the body:
// "attachments": [{"filename": "invoice-1042.pdf", "content": "<content>", "content_type": "application/pdf"}]

Keep attachments small. Large files are better shared as a signed download link, which also keeps the message under receiving servers’ size limits.

Option 2: Jakarta Mail over SMTP

JavaMail was renamed Jakarta Mail when Java EE moved to the Eclipse Foundation, and its package changed from javax.mail to jakarta.mail. The maintained implementation is Eclipse Angus Mail. One Maven dependency pulls in both the API and the implementation:

<dependency>
  <groupId>org.eclipse.angus</groupId>
  <artifactId>angus-mail</artifactId>
  <version>2.0.5</version>
</dependency>
import jakarta.mail.Authenticator;
import jakarta.mail.Message;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import java.util.Properties;

public class SendSmtp {
    public static void main(String[] args) throws Exception {
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.mailcandor.com");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.connectiontimeout", "10000");
        props.put("mail.smtp.timeout", "10000");

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("mailcandor", System.getenv("MAILCANDOR_KEY"));
            }
        });

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("hello@acme.com", "Acme"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("sam@example.com"));
        message.setSubject("Your login code");
        message.setContent("<p>Your code is <b>481 203</b></p>", "text/html; charset=utf-8");

        Transport.send(message);
    }
}

To use port 587 instead, set mail.smtp.port to 587, remove mail.smtp.ssl.enable, and add mail.smtp.starttls.enable and mail.smtp.starttls.required set to true. The second property matters: without it, Jakarta Mail will carry on unencrypted if the server does not offer STARTTLS. The SMTP ports guide explains 465 versus 587.

Set the timeouts. Jakarta Mail waits forever by default, so a stalled server can hang a thread indefinitely.

For HTML plus a text fallback, or attachments, build a MimeMultipart("alternative") with one MimeBodyPart per version.

Which should you choose?

HttpClient + email API Jakarta Mail + SMTP
Dependencies None (JDK 11+) angus-mail
Per email One HTTPS request SMTP session per Transport.send
Delivery events Webhooks by email id Not part of SMTP
Retry safety Idempotency-Key header Your own de-duplication
Best for Services, workers, cloud functions Legacy apps, SMTP-only systems

Errors and retries

An email API answers with a JSON error such as {"error": {"type": "...", "message": "...", "field": "from"}}. Retry only on 429 and 5xx responses, with backoff. Mailcandor sends ratelimit-* headers so you can see how close you are to your team’s limit (5 requests a second on Starter, 10 on Pay as you go, 50 on Team).

With SMTP, MessagingException covers everything from a refused login to a rejected recipient. Log the server reply in the exception message; it usually names the cause.

Before you send: verify your domain

Mail from a domain without SPF, DKIM and DMARC records is likely to be filtered as spam. Add your domain in your provider’s dashboard, publish the records it gives you, and wait for them to verify. The SPF, DKIM and DMARC setup guide explains each one.

Sending with Mailcandor

Mailcandor offers both paths with the same key: the email API and an SMTP relay at smtp.mailcandor.com on port 465 or 587, username mailcandor, password your API key. There is no Java SDK to add; the JDK or Angus Mail is enough. Access is by request through the pricing page, and the Starter plan includes 3,000 emails a month free.

Questions

Is JavaMail still used?

JavaMail became Jakarta Mail when Java EE moved to the Eclipse Foundation, and the package changed from javax.mail to jakarta.mail. The current implementation is Eclipse Angus Mail. Old javax.mail code needs its imports updated.

Which Maven dependency do I need for Jakarta Mail?

Add org.eclipse.angus:angus-mail. It brings in the jakarta.mail-api it implements, so one dependency is enough.

How do I send email in Java without a library?

Use java.net.http.HttpClient, which ships with the JDK, to POST JSON to an email API. There is no SMTP client in the JDK itself.

Should I use port 465 or 587 with Jakarta Mail?

Either works. For 465 set mail.smtp.ssl.enable to true. For 587 set mail.smtp.starttls.enable and mail.smtp.starttls.required to true so the connection is always encrypted.

Related

Send with someone on your side.

Unlimited domains on every plan, a person before any block, and 3,000 emails a month free. Tell us what you send and we set you up within one business day.