Frameworks

How to send email in Spring Boot

Short answer

To send email in Spring Boot, add spring-boot-starter-mail, set spring.mail.host, port, username and password, and inject JavaMailSender. Boot creates the sender for you as soon as spring.mail.host is set. If you would rather call an email API, use RestClient to POST JSON instead. Both work in Spring Boot 4; set mail timeouts, send from a background thread, and verify your domain first.

Last checked 16 November 2026

Spring Boot sends email through JavaMailSender, which the mail starter configures for you from spring.mail.* properties. Add the starter, point it at an SMTP server, inject the sender and call send. If you prefer an email API over SMTP, Spring’s RestClient sends the same email as one HTTPS request. This guide covers both for Spring Boot 4.

Option 1: spring-boot-starter-mail and JavaMailSender

Add the starter. It brings in Jakarta Mail (the Eclipse Angus implementation) and Spring’s mail support.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

With Gradle: implementation("org.springframework.boot:spring-boot-starter-mail").

Configure the SMTP server

Put the settings in application.yml. Keep the password in an environment variable, never in the file:

spring:
  mail:
    host: smtp.mailcandor.com
    port: 587
    username: mailcandor
    password: ${MAILCANDOR_KEY}
    properties:
      "[mail.smtp.auth]": true
      "[mail.smtp.starttls.enable]": true
      "[mail.smtp.starttls.required]": true
      "[mail.smtp.connectiontimeout]": 5000
      "[mail.smtp.timeout]": 5000
      "[mail.smtp.writetimeout]": 5000

The bracket notation keeps the dots inside JavaMail property names intact, as the Spring Boot email docs show. Set the three timeouts: the docs point out that some JavaMail defaults are infinite, so an unresponsive server can block a thread for good.

Port 587 with starttls.required always encrypts the connection. For port 465, set port: 465 and replace the STARTTLS lines with "[mail.smtp.ssl.enable]": true. The SMTP ports guide explains the two modes.

As soon as spring.mail.host is set, Boot registers a JavaMailSender bean.

Send an HTML email

SimpleMailMessage only does plain text. For HTML, use MimeMessageHelper:

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class MailService {
    private final JavaMailSender mailSender;

    public MailService(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    @Async
    public void sendLoginCode(String to, String code) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        helper.setFrom("hello@acme.com");
        helper.setTo(to);
        helper.setSubject("Your login code");
        helper.setText(
            "Your code is " + code,                              // plain text
            "<p>Your code is <b>" + code + "</b></p>"            // HTML
        );
        mailSender.send(message);
    }
}

The two-argument setText(plain, html) builds a multipart message with both versions, which helps deliverability. Attach files with helper.addAttachment("invoice.pdf", resource).

@Async runs the method on a background thread so the web request returns at once. It only takes effect if a configuration class has @EnableAsync, and only when the method is called from another bean, not from inside MailService itself.

If you render templates with Thymeleaf, process the template to a string with TemplateEngine.process and pass the result to setText.

Option 2: RestClient and an email API

An email API replaces the SMTP session with one HTTPS request and gives you an id to track delivery. RestClient is Spring’s synchronous HTTP client and is available whenever Spring Web is on the classpath. This example uses Mailcandor:

import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;

@Service
public class EmailApi {
    private final RestClient client;

    public EmailApi(@Value("${MAILCANDOR_KEY}") String key) {
        this.client = RestClient.builder()
            .baseUrl("https://api.mailcandor.com/v1")
            .defaultHeader("Authorization", "Bearer " + key)
            .build();
    }

    public String send(String to, String subject, String html, String idempotencyKey) {
        Map<?, ?> result = client.post()
            .uri("/emails")
            .contentType(MediaType.APPLICATION_JSON)
            .header("Idempotency-Key", idempotencyKey)
            .body(Map.of(
                "from", "Acme <hello@acme.com>",
                "to", to,
                "subject", subject,
                "html", html))
            .retrieve()
            .body(Map.class);
        return (String) result.get("id");
    }
}

retrieve() throws a RestClientResponseException on any 4xx or 5xx response; its body holds {"error": {"type", "message", "field"}}, which tells you what to fix. Retry only on 429 and 5xx. The Idempotency-Key makes those retries safe: a repeated key returns the first response instead of sending again. A Java record works as the body too, in place of the Map.

The API returns 202 with {"id": "...", "status": "queued"}. Delivery, bounces and complaints arrive later as webhooks, which you can receive in an ordinary @PostMapping controller.

Which should you choose?

JavaMailSender (SMTP) RestClient (email API)
Setup Starter plus spring.mail.* Spring Web, one class
Test with a local SMTP catcher Yes Needs a stub server
Delivery tracking Not part of SMTP Webhooks by email id
Safe retries No built-in support Idempotency-Key header
Batch sending One session per send Up to 100 emails per request

Many teams keep JavaMailSender because the rest of their code and tests already use it, and just point it at a better relay. Either choice is fine. The plain Java guide has the same two approaches without Spring.

Testing without sending real email

In development, point spring.mail.host at a local SMTP catcher such as Mailpit, which listens on port 1025 by default and shows every message in a web inbox. Put those settings in an application-dev.yml profile so production values never change. For the RestClient route, MockRestServiceServer from spring-test can bind to the builder and assert on the outgoing request body and headers without a network call.

If you are still on Spring Boot 3, everything in this guide applies unchanged: the spring.mail properties, JavaMailSender and RestClient all work the same way.

Before you send: verify your domain

Mail from a domain without SPF, DKIM and DMARC is likely to be marked as spam, no matter how you send it. Add your domain in your provider’s dashboard and publish the DNS records it gives you. See the SPF, DKIM and DMARC setup guide.

Sending with Mailcandor

Mailcandor works with both options. The SMTP relay takes the spring.mail settings above as they are, and the email API takes the RestClient call. There is no Mailcandor Java SDK; Spring’s own classes are all you need. Access is by request through the pricing page, with 3,000 emails a month free on Starter.

Questions

How do I configure SMTP in Spring Boot?

Add spring-boot-starter-mail and set spring.mail.host, spring.mail.port, spring.mail.username and spring.mail.password. Extra JavaMail settings such as STARTTLS go under spring.mail.properties. Boot then provides a JavaMailSender bean.

Why is my JavaMailSender bean missing?

Boot only creates it when spring.mail.host is set and the mail starter is on the classpath. Check the property name and that it is set in the active profile.

How do I send HTML email in Spring Boot?

Use a MimeMessage with MimeMessageHelper and call setText(html, true). SimpleMailMessage only sends plain text.

Should email sending be async in Spring Boot?

Usually yes. Annotate the sending method with @Async (and enable it with @EnableAsync) or put the email on a queue, so a slow mail server never slows down the web request.

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.