How to Send Email in Java: Jakarta Mail, Spring Boot and API
Pranav Patel
Co-founderยท13 min read
On this page

Send email from Java with Jakarta Mail, Spring Boot's JavaMailSender, or an email API. Copy-paste examples for HTML email, attachments, background sending and retries without duplicates.
Java sends email over SMTP with Jakarta Mail, the library formerly known as JavaMail. Spring Boot wraps it as JavaMailSender. For anything in production, send through a provider: either over SMTP with Jakarta Mail or Spring's spring.mail.* settings, or over HTTPS with an email API SDK.
This guide covers plain Jakarta Mail, the Reloop Java SDK and Spring Boot, then the production details: attachments, background sending and safe retries.
Working in another language? See how to send email in Node.js or in Python.
Which approach should you use?
JavaMailSenderangus-mail, or spring-boot-starter-mailsh.reloop:reloop-javaMimeMessage, MimeMultipart, MimeMessageHelperSendMailParams object with html, text, attachmentsMessagingException or Spring's MailExceptionReloopApiException with an HTTP statusJavaMailSenderIf a framework or library already sends mail through JavaMailSender, use SMTP settings. If you are writing the send call yourself, use the API.
Prerequisites
- Java 17 or later (Spring Boot 3 requires it)
- A verified sending domain with SPF, DKIM and DMARC
- An API key from the Reloop dashboard. Keys start with
rl_, and the same key works for the API and SMTP.
export RELOOP_API_KEY=rl_your_api_keyKeep the key in the environment or a secrets manager, never in your code or git.
Method 1: Send email with Jakarta Mail
JavaMail was renamed Jakarta Mail when it moved to the Eclipse Foundation. Version 2.0 changed the package from javax.mail to jakarta.mail, so old tutorials that import javax.mail.* will not compile against current libraries or Spring Boot 3. The implementation is now called Angus Mail:
1<dependency>2 <groupId>org.eclipse.angus</groupId>3 <artifactId>angus-mail</artifactId>4 <version>2.0.5</version>5</dependency>It pulls in the jakarta.mail-api package. Then build a MimeMessage with a plain-text part and an HTML part:
1import jakarta.mail.Authenticator;2import jakarta.mail.Message;3import jakarta.mail.MessagingException;4import jakarta.mail.PasswordAuthentication;5import jakarta.mail.Session;6import jakarta.mail.Transport;7import jakarta.mail.internet.InternetAddress;8import jakarta.mail.internet.MimeBodyPart;9import jakarta.mail.internet.MimeMessage;10import jakarta.mail.internet.MimeMultipart;11import java.util.Properties;12
13public class SendWelcome {14 public static void main(String[] args) throws MessagingException {15 Properties props = new Properties();16 props.put("mail.smtp.host", "smtp.reloop.sh");17 props.put("mail.smtp.port", "587");18 props.put("mail.smtp.auth", "true");19 props.put("mail.smtp.starttls.enable", "true");20 props.put("mail.smtp.starttls.required", "true");21 props.put("mail.smtp.connectiontimeout", "10000");22 props.put("mail.smtp.timeout", "30000");23 props.put("mail.smtp.writetimeout", "30000");24
25 Session session = Session.getInstance(props, new Authenticator() {26 @Override27 protected PasswordAuthentication getPasswordAuthentication() {28 return new PasswordAuthentication("reloop", System.getenv("RELOOP_API_KEY"));29 }30 });31
32 MimeMessage message = new MimeMessage(session);33 message.setFrom(new InternetAddress("Acme <hello@mail.acme.com>"));34 message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("user@example.com"));35 message.setSubject("Welcome to Acme", "UTF-8");36
37 // Plain-text part first, then the HTML alternative38 MimeBodyPart text = new MimeBodyPart();39 text.setText("Welcome! Thanks for signing up.", "UTF-8");40
41 MimeBodyPart html = new MimeBodyPart();42 html.setContent("<h1>Welcome!</h1><p>Thanks for signing up.</p>", "text/html; charset=UTF-8");43
44 MimeMultipart body = new MimeMultipart("alternative");45 body.addBodyPart(text);46 body.addBodyPart(html);47 message.setContent(body);48
49 Transport.send(message);50 }51}The username can be any string. The password is your API key.
starttls.enable upgrades the connection to TLS, and starttls.required makes the send fail instead of falling back to plain text if the upgrade does not happen. Set the timeouts too: Jakarta Mail waits forever by default, which can hang a thread when the network misbehaves.
When port 587 is blocked
Some hosts block outbound 587. Reloop also accepts STARTTLS on port 2587 (and 2025), so only the port number changes:
props.put("mail.smtp.port", "2587");Reloop does not offer implicit TLS on port 465, so do not set mail.smtp.ssl.enable or use the smtps protocol with it. If the connection hangs or times out, see SMTP ports explained.
Handle SMTP errors
1try {2 Transport.send(message);3} catch (AuthenticationFailedException e) {4 System.err.println("Wrong API key");5} catch (SendFailedException e) {6 System.err.println("Rejected recipients: " + Arrays.toString(e.getInvalidAddresses()));7} catch (MessagingException e) {8 System.err.println("Send failed: " + e.getMessage());9}Both AuthenticationFailedException and SendFailedException extend MessagingException, so catch them first.
Can I send with Gmail from Java?
For a personal script, yes: use smtp.gmail.com on port 587 with an App Password. For an app, no. Gmail limits personal accounts to about 500 recipients a day, every message comes from your @gmail.com address, and bulk sending gets the account suspended.
Method 2: Send email with the Java SDK
Install
Maven:
1<dependency>2 <groupId>sh.reloop</groupId>3 <artifactId>reloop-java</artifactId>4 <version>2.0.0</version>5</dependency>Gradle:
implementation("sh.reloop:reloop-java:2.0.0")The SDK uses the JDK's built-in java.net.http.HttpClient and Jackson, so it adds no HTTP library to your build.
Send an email
1import sh.reloop.ReloopClient;2import sh.reloop.exceptions.ReloopApiException;3import sh.reloop.models.MailModels.SendMailParams;4import sh.reloop.models.MailModels.SendMailResponse;5
6public class SendWelcome {7 public static void main(String[] args) {8 ReloopClient reloop = new ReloopClient(System.getenv("RELOOP_API_KEY"));9
10 SendMailParams params = new SendMailParams();11 params.from = "Acme <hello@mail.acme.com>";12 params.to = "user@example.com";13 params.subject = "Welcome to Acme";14 params.html = "<h1>Welcome!</h1><p>Thanks for signing up.</p>";15 params.text = "Welcome! Thanks for signing up.";16
17 try {18 SendMailResponse result = reloop.mail.send(params);19 System.out.println("Sent: " + result.id);20 } catch (ReloopApiException e) {21 System.err.println("Failed: " + e.getStatus() + " " + e.getMessage());22 }23 }24}The SDK throws unchecked exceptions:
ReloopApiExceptionfor any non-2xx response or network failure.getStatus()returns the HTTP status, or0when the request never got a response.getBody()holds the API'smessageandwhy.ReloopValidationExceptionwhenfrom,toorsubjectis missing. It is thrown before any HTTP call.
Create the client once and reuse it. It wraps a single HttpClient, which is safe to share between threads, and there is nothing to close. Requests time out after 30 seconds.
Send to several recipients
to, cc, bcc and replyTo take either one address or a list:
1import java.util.List;2import sh.reloop.models.MailModels.SendMailTag;3
4SendMailParams params = new SendMailParams();5params.from = "Acme <hello@mail.acme.com>";6params.to = List.of("ada@example.com", "grace@example.com");7params.cc = "team@acme.com";8params.replyTo = "support@acme.com";9params.subject = "Your weekly report";10params.text = "Here is your report.";11params.tags = List.of(new SendMailTag("type", "weekly_report"));12
13reloop.mail.send(params);Every address in to sees the others. For personalized mail, send one message per recipient.
Send a stored template
Keep copy out of your code so non-developers can edit it. Create the template in Reloop, then send it by ID with variables:
1import java.util.Map;2import sh.reloop.models.MailModels.SendMailTemplate;3
4SendMailTemplate template = new SendMailTemplate();5template.id = "tmpl_welcome";6template.variables = Map.of("first_name", "Ada", "plan", "Pro");7
8SendMailParams params = new SendMailParams();9params.from = "Acme <hello@mail.acme.com>";10params.to = "user@example.com";11params.subject = "Welcome to Acme";12params.template = template;13
14reloop.mail.send(params);See templates for variables and defaults.
Spring Boot
SMTP with spring-boot-starter-mail
Add the starter. It brings in Angus Mail and auto-configures a JavaMailSender bean from spring.mail.* properties:
1<dependency>2 <groupId>org.springframework.boot</groupId>3 <artifactId>spring-boot-starter-mail</artifactId>4</dependency>1spring.mail.host=smtp.reloop.sh2spring.mail.port=5873spring.mail.username=reloop4spring.mail.password=${RELOOP_API_KEY}5spring.mail.properties.mail.smtp.auth=true6spring.mail.properties.mail.smtp.starttls.enable=true7spring.mail.properties.mail.smtp.starttls.required=true8spring.mail.properties.mail.smtp.connectiontimeout=100009spring.mail.properties.mail.smtp.timeout=3000010spring.mail.properties.mail.smtp.writetimeout=30000Everything under spring.mail.properties is passed straight to Jakarta Mail, so these are the same settings as Method 1. Keep mail.smtp.ssl.enable off: Reloop uses STARTTLS, not implicit TLS. If 587 is blocked, set spring.mail.port=2587.
Use MimeMessageHelper to build a message with both bodies:
1import jakarta.mail.MessagingException;2import jakarta.mail.internet.MimeMessage;3import org.springframework.mail.javamail.JavaMailSender;4import org.springframework.mail.javamail.MimeMessageHelper;5import org.springframework.stereotype.Service;6
7@Service8public class WelcomeMailer {9 private final JavaMailSender mailSender;10
11 public WelcomeMailer(JavaMailSender mailSender) {12 this.mailSender = mailSender;13 }14
15 public void sendWelcome(String to) throws MessagingException {16 MimeMessage message = mailSender.createMimeMessage();17 // true = multipart, needed for text + HTML and for attachments18 MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");19 helper.setFrom("Acme <hello@mail.acme.com>");20 helper.setTo(to);21 helper.setSubject("Welcome to Acme");22 helper.setText(23 "Welcome! Thanks for signing up.",24 "<h1>Welcome!</h1><p>Thanks for signing up.</p>");25 mailSender.send(message);26 }27}setText(plain, html) only works when the helper is in multipart mode. mailSender.send throws Spring's unchecked MailException: MailAuthenticationException for a wrong key and MailSendException for connection or recipient failures.
The SDK as a Spring bean
Register one ReloopClient for the whole application:
1import org.springframework.beans.factory.annotation.Value;2import org.springframework.context.annotation.Bean;3import org.springframework.context.annotation.Configuration;4import sh.reloop.ReloopClient;5
6@Configuration7public class ReloopConfig {8 @Bean9 public ReloopClient reloopClient(@Value("${reloop.api-key}") String apiKey) {10 return new ReloopClient(apiKey);11 }12}reloop.api-key=${RELOOP_API_KEY}Then inject it into a @Service:
1import org.springframework.stereotype.Service;2import sh.reloop.ReloopClient;3import sh.reloop.models.MailModels.SendMailParams;4
5@Service6public class ContactMailer {7 private final ReloopClient reloop;8
9 public ContactMailer(ReloopClient reloop) {10 this.reloop = reloop;11 }12
13 public String forward(String visitorEmail, String message) {14 SendMailParams params = new SendMailParams();15 params.from = "Acme Website <contact@mail.acme.com>";16 params.to = "support@acme.com";17 params.replyTo = visitorEmail;18 params.subject = "New message from " + visitorEmail;19 params.text = message;20 return reloop.mail.send(params).id;21 }22}And call it from a controller:
1import jakarta.validation.Valid;2import jakarta.validation.constraints.Email;3import jakarta.validation.constraints.NotBlank;4import java.util.Map;5import org.springframework.http.HttpStatus;6import org.springframework.web.bind.annotation.PostMapping;7import org.springframework.web.bind.annotation.RequestBody;8import org.springframework.web.bind.annotation.RestController;9import org.springframework.web.server.ResponseStatusException;10import sh.reloop.exceptions.ReloopApiException;11
12@RestController13public class ContactController {14 private final ContactMailer contactMailer;15
16 public ContactController(ContactMailer contactMailer) {17 this.contactMailer = contactMailer;18 }19
20 public record ContactRequest(@Email @NotBlank String email, @NotBlank String message) {}21
22 @PostMapping("/contact")23 public Map<String, String> contact(@Valid @RequestBody ContactRequest body) {24 try {25 return Map.of("id", contactMailer.forward(body.email(), body.message()));26 } catch (ReloopApiException e) {27 throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, "Could not send message", e);28 }29 }30}The validation annotations need spring-boot-starter-validation. The visitor's address goes in replyTo, never in from. You can only send from your verified domain, and putting someone else's domain in from fails DMARC.
Quarkus
Quarkus has its own mailer extension, quarkus-mailer, configured the same way:
1quarkus.mailer.from=Acme <hello@mail.acme.com>2quarkus.mailer.host=smtp.reloop.sh3quarkus.mailer.port=5874quarkus.mailer.start-tls=REQUIRED5quarkus.mailer.username=reloop6quarkus.mailer.password=${RELOOP_API_KEY}Inject io.quarkus.mailer.Mailer and call mailer.send(Mail.withHtml(to, subject, html)). In dev and test mode the mailer is mocked by default and does not send anything. The Java SDK also works in Quarkus: produce a ReloopClient from a CDI producer method, just like the Spring @Bean above.
Attachments
With the SDK, pass base64 content:
1import java.nio.file.Files;2import java.nio.file.Path;3import java.util.Base64;4import java.util.List;5import sh.reloop.models.MailModels.SendMailAttachment;6
7byte[] pdf = Files.readAllBytes(Path.of("invoice-1042.pdf"));8
9SendMailAttachment invoice = new SendMailAttachment();10invoice.filename = "invoice-1042.pdf";11invoice.content = Base64.getEncoder().encodeToString(pdf);12invoice.contentType = "application/pdf";13
14SendMailParams params = new SendMailParams();15params.from = "Acme Billing <billing@mail.acme.com>";16params.to = "user@example.com";17params.subject = "Your invoice #1042";18params.text = "Your invoice is attached.";19params.attachments = List.of(invoice);20
21reloop.mail.send(params);With Spring's MimeMessageHelper in multipart mode, call addAttachment:
helper.addAttachment("invoice-1042.pdf", new FileSystemResource("invoice-1042.pdf"));With plain Jakarta Mail, wrap the text and HTML in a mixed multipart next to the file:
1MimeBodyPart content = new MimeBodyPart();2content.setContent(body); // the "alternative" multipart from Method 13
4MimeBodyPart pdf = new MimeBodyPart();5pdf.attachFile(new File("invoice-1042.pdf"), "application/pdf", null);6
7MimeMultipart mixed = new MimeMultipart("mixed");8mixed.addBodyPart(content);9mixed.addBodyPart(pdf);10message.setContent(mixed);Keep attachments small. Many inboxes reject messages over 25 MB, and large files hurt deliverability. For big files, send a signed download link.
Send in the background with @Async
Sending inside a web request adds latency and fails the request when the provider is slow. In Spring Boot, the quickest fix is @Async. Turn it on once:
1import org.springframework.boot.SpringApplication;2import org.springframework.boot.autoconfigure.SpringBootApplication;3import org.springframework.scheduling.annotation.EnableAsync;4
5@SpringBootApplication6@EnableAsync7public class Application {8 public static void main(String[] args) {9 SpringApplication.run(Application.class, args);10 }11}Then mark the send method @Async and retry only the errors that can succeed on a second try:
1import org.slf4j.Logger;2import org.slf4j.LoggerFactory;3import org.springframework.scheduling.annotation.Async;4import org.springframework.stereotype.Service;5import sh.reloop.ReloopClient;6import sh.reloop.exceptions.ReloopApiException;7import sh.reloop.models.MailModels.SendMailParams;8
9@Service10public class SignupMailer {11 private static final Logger log = LoggerFactory.getLogger(SignupMailer.class);12 private static final int MAX_ATTEMPTS = 5;13
14 private final ReloopClient reloop;15
16 public SignupMailer(ReloopClient reloop) {17 this.reloop = reloop;18 }19
20 @Async21 public void sendWelcome(String email) throws InterruptedException {22 SendMailParams params = new SendMailParams();23 params.from = "Acme <hello@mail.acme.com>";24 params.to = email;25 params.subject = "Welcome to Acme";26 params.text = "Thanks for signing up.";27
28 for (int attempt = 1; ; attempt++) {29 try {30 reloop.mail.send(params);31 return;32 } catch (ReloopApiException e) {33 if (!isRetryable(e) || attempt == MAX_ATTEMPTS) {34 log.error("Welcome email to {} failed: {} {}", email, e.getStatus(), e.getMessage());35 throw e;36 }37 Thread.sleep(1000L * (1L << attempt)); // 2s, 4s, 8s, 16s38 }39 }40 }41
42 private static boolean isRetryable(ReloopApiException e) {43 int status = e.getStatus();44 return status == 0 || status == 429 || status >= 500;45 }46}Retry network errors (status 0), 429 and 5xx. Do not retry other 4xx errors: an invalid address or unverified domain fails the same way every time.
Call sendWelcome from another bean, such as your controller, and it returns immediately. Calling it from inside SignupMailer itself skips the proxy and runs synchronously.
@Async runs on an in-memory thread pool, so pending emails are lost if the process restarts. For emails that must arrive, write a row to an outbox table in the same transaction as the business change and have a scheduled worker send pending rows, or hand the job to a persistent queue such as RabbitMQ, SQS or a job library like JobRunr.
Retries without duplicate emails
A request times out and your code retries. If the first attempt actually went through, the user gets two emails. The API prevents this with an Idempotency-Key header: repeat a request with the same key and Reloop returns the original result instead of sending again.
The Java SDK does not set this header yet, so call the endpoint with java.net.http.HttpClient. Jackson is already on your classpath through the SDK:
1import com.fasterxml.jackson.databind.ObjectMapper;2import java.io.IOException;3import java.net.URI;4import java.net.http.HttpClient;5import java.net.http.HttpRequest;6import java.net.http.HttpResponse;7import java.time.Duration;8import java.util.Map;9
10public class ReceiptSender {11 private static final HttpClient HTTP = HttpClient.newBuilder()12 .connectTimeout(Duration.ofSeconds(10))13 .build();14 private static final ObjectMapper JSON = new ObjectMapper();15
16 public static String sendReceipt(String orderId, String to)17 throws IOException, InterruptedException {18 String body = JSON.writeValueAsString(Map.of(19 "from", "Acme <orders@mail.acme.com>",20 "to", to,21 "subject", "Receipt for order " + orderId,22 "text", "Thanks for your order."));23
24 HttpRequest request = HttpRequest.newBuilder()25 .uri(URI.create("https://reloop.sh/api/mail/v1/send"))26 .timeout(Duration.ofSeconds(30))27 .header("x-api-key", System.getenv("RELOOP_API_KEY"))28 .header("Content-Type", "application/json")29 .header("Idempotency-Key", "receipt-" + orderId)30 .POST(HttpRequest.BodyPublishers.ofString(body))31 .build();32
33 HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());34 if (response.statusCode() >= 400) {35 throw new IOException("Send failed: " + response.statusCode() + " " + response.body());36 }37 return JSON.readTree(response.body()).get("id").asText();38 }39}Base the key on the business event (receipt- plus the order ID), not a new UUID per attempt, so retries from any thread or server are safe. A 409 means a request with that key is still running: wait a second and retry with the same key.
Testing without sending real email
- Unit tests: put the SDK behind your own small interface (for example
Mailer) and mock that.ReloopClient.mailis a final field, so mocking the client directly is awkward. - Integration tests: GreenMail runs an in-memory SMTP server inside JUnit 5. Register
GreenMailExtensionwithServerSetupTest.SMTP, point aJavaMailSenderImplatlocalhost:3025, and assert ongreenMail.getReceivedMessages(). - Local SMTP: run Mailpit with
docker run -p 1025:1025 -p 8025:8025 axllent/mailpitand point a dev profile at it. Openhttp://localhost:8025to see the messages.
1spring.mail.host=localhost2spring.mail.port=10253spring.mail.username=4spring.mail.password=5spring.mail.properties.mail.smtp.auth=false6spring.mail.properties.mail.smtp.starttls.enable=false7spring.mail.properties.mail.smtp.starttls.required=falseIn staging, send to test addresses so you do not hurt your sender reputation with bounces.
Production checklist
- API key in an environment variable or secrets manager
- Sending domain verified with SPF, DKIM and DMARC
-
fromon your verified domain; user addresses inreplyTo - Both HTML and plain-text bodies
- One shared
ReloopClientbean, created at startup - SMTP timeouts set (
connectiontimeout,timeout,writetimeout) - Sending off the request thread (
@Async, an outbox or a queue) - Retries only on network errors,
429and5xx - Idempotency keys on anything that retries
- Webhooks for bounces and complaints
- Disposable addresses blocked at signup (how)
FAQ
With Jakarta Mail, build a MimeMultipart of type alternative with a plain-text MimeBodyPart and an HTML MimeBodyPart set to text/html. With Spring, create a MimeMessageHelper in multipart mode and call setText with both bodies. With the Reloop SDK, set html and text on SendMailParams.
They are the same library under two names. Jakarta Mail 2.0 moved the package from javax.mail to jakarta.mail. Spring Boot 3 and current application servers use jakarta.mail, so replace the javax.mail imports and the old com.sun.mail dependency with Angus Mail.
Use 587 with mail.smtp.starttls.enable and mail.smtp.starttls.required set to true. Port 465 expects implicit TLS through mail.smtp.ssl.enable, which Reloop does not offer. If 587 is blocked, use 2587 with the same STARTTLS settings.
The client holds no per-request state and sends through a single java.net.http.HttpClient, which is safe to share between threads. Create one ReloopClient at startup, for example as a Spring bean, and use it everywhere.
Usually the sending domain is not authenticated, or the From domain does not match the domain that signed the message. Set up SPF, DKIM and DMARC, send from your own domain, and always include a plain-text body.
Ship your first email with Reloop
in minutes.
Open-source, deliverability-focused, and yours to self-host or run on Reloop Cloud. No lock-in, no rewrite later.


