00:00

Sending Email with Spring Boot

Last updated:

Sending email with Spring Boot takes one starter and a few properties: add spring-boot-starter-mail, point spring.mail.* at an SMTP server, and inject the auto-configured JavaMailSender. From there you can send plain-text messages, HTML emails with images, and attachments such as invoices. The harder part is sending email reliably: not from inside a database transaction, not on the request thread, and not to real customers while you test.

This tutorial covers the setup, plain and HTML messages, attachments, sending an order confirmation only after the order is committed and in the background, testing against a local mail catcher, and the common configuration mistakes.

1. How Email Sending Works in Spring Boot

Applications send email through SMTP (Simple Mail Transfer Protocol) to a mail server: your company's server, or a provider such as Amazon SES, SendGrid or Mailgun. Java's standard API for this is Jakarta Mail. Spring wraps it in the JavaMailSender interface, and Spring Boot auto-configures a JavaMailSenderImpl bean as soon as spring.mail.host is set.

Sending an order confirmation email from Spring BootThe order service commits the order and publishes an OrderPlaced event. After the transaction commits, an asynchronous listener builds a MimeMessage with MimeMessageHelper and sends it through the auto-configured JavaMailSender, which connects to the SMTP server configured with spring.mail properties. The SMTP server delivers the email to the customer's mailbox. OrderService saves order, publishes event Mail listener after commit, @Async JavaMailSender MimeMessageHelper builds the message SMTP server spring.mail.host / port delivers to customer
Publish an event, send after commit on a background thread, and let JavaMailSender talk to the SMTP server.

2. Dependency and SMTP Configuration

pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
application.properties
spring.mail.host=smtp.example.com
spring.mail.port=587
spring.mail.username=${MAIL_USERNAME}
spring.mail.password=${MAIL_PASSWORD}
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000
shop.mail.from=Shop <orders@shop.example.com>
PropertyMeaning
spring.mail.host, spring.mail.portSMTP server; port 587 with STARTTLS is the usual choice for submission
spring.mail.username, spring.mail.passwordCredentials; keep them out of the file, see managing secrets
spring.mail.properties.*Any Jakarta Mail session property, such as STARTTLS and timeouts
spring.mail.default-encodingMessage encoding, UTF-8 by default
spring.mail.test-connectionCheck the connection at startup (off by default)

Always set the timeouts: Jakarta Mail waits indefinitely by default, so an unreachable mail server could block a thread forever. With Actuator, a mail health indicator also reports whether the server is reachable.

The custom property shop.mail.from holds the sender address: Shop <orders@shop.example.com>.

3. Sending a Plain-Text Email

WelcomeMailer.java
package com.javabytechie.shop.mail;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

@Component
public class WelcomeMailer {

    private final JavaMailSender mailSender;
    private final String from;

    public WelcomeMailer(JavaMailSender mailSender, @Value("${shop.mail.from}") String from) {
        this.mailSender = mailSender;
        this.from = from;
    }

    public void sendWelcome(String email, String firstName) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(email);
        message.setSubject("Welcome to the shop, " + firstName);
        message.setText("Hi " + firstName + ",\n\nThanks for creating an account.\n\nThe Shop team");
        mailSender.send(message);
    }
}

SimpleMailMessage is enough for short text notifications. Failures throw a MailException, an unchecked exception with subclasses such as MailAuthenticationException and MailSendException.

4. HTML Emails and Attachments with MimeMessageHelper

For HTML, inline images or attachments, create a MimeMessage and fill it with MimeMessageHelper. Pass true for multipart mode whenever you add attachments or inline resources, and send both a plain-text and an HTML version so every mail client can show something.

MimeMessageHelper example
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");   // multipart
helper.setFrom(from);
helper.setTo("asha@example.com");
helper.setSubject("Your invoice INV-1001");
helper.setText("Your invoice is attached.", "<p>Your invoice is <b>attached</b>.</p>");  // text, html
helper.addAttachment("INV-1001.pdf", new ByteArrayResource(pdfBytes), "application/pdf");
mailSender.send(message);

For larger HTML emails, render the body with a template engine such as Thymeleaf rather than building strings in Java, and keep the CSS inline, because many mail clients ignore style sheets.

5. A Complete Example: Order Confirmation After Commit

The order confirmation must only be sent if the order really was saved, and the customer should not wait for the SMTP server. The order service publishes an event; a listener sends the email after the transaction commits, on a background thread.

5.1 The Event and the Order Service

OrderPlaced.java
package com.javabytechie.shop.order;

import java.math.BigDecimal;

public record OrderPlaced(String orderId, String customerEmail, String customerName, BigDecimal total) {
}
OrderService.java
package com.javabytechie.shop.order;

import java.math.BigDecimal;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderService {

    private final ApplicationEventPublisher events;

    public OrderService(ApplicationEventPublisher events) {
        this.events = events;
    }

    @Transactional
    public String place(String customerEmail, String customerName, BigDecimal total) {
        String orderId = "ORD-" + System.currentTimeMillis() % 100000;
        // save the order with a repository here
        events.publishEvent(new OrderPlaced(orderId, customerEmail, customerName, total));
        return orderId;
    }
}

5.2 The Mail Listener

OrderConfirmationMailer.java
package com.javabytechie.shop.mail;

import com.javabytechie.shop.order.OrderPlaced;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;
import org.springframework.web.util.HtmlUtils;

@Component
public class OrderConfirmationMailer {

    private static final Logger log = LoggerFactory.getLogger(OrderConfirmationMailer.class);
    private final JavaMailSender mailSender;
    private final String from;

    public OrderConfirmationMailer(JavaMailSender mailSender, @Value("${shop.mail.from}") String from) {
        this.mailSender = mailSender;
        this.from = from;
    }

    @Async
    @TransactionalEventListener   // default phase: AFTER_COMMIT
    public void onOrderPlaced(OrderPlaced event) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(from);
            helper.setTo(event.customerEmail());
            helper.setSubject("Order " + event.orderId() + " confirmed");
            String name = HtmlUtils.htmlEscape(event.customerName());
            helper.setText(
                    "Hi " + event.customerName() + ", your order " + event.orderId() + " for EUR " + event.total() + " is confirmed.",
                    "<p>Hi " + name + ",</p><p>Your order <b>" + event.orderId() + "</b> for <b>EUR "
                            + event.total() + "</b> is confirmed.</p>");
            mailSender.send(message);
            log.info("Confirmation for order {} sent to {}", event.orderId(), event.customerEmail());
        } catch (MessagingException | MailException ex) {
            log.error("Could not send confirmation for order {}", event.orderId(), ex);
        }
    }
}

5.3 Enabling Async Execution

AsyncConfig.java
package com.javabytechie.shop.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

@Configuration(proxyBeanMethods = false)
@EnableAsync
class AsyncConfig {
}

@TransactionalEventListener runs only if the transaction commits, so a rolled-back order never triggers an email. @Async moves the SMTP call off the request thread. Customer names are HTML-escaped before going into the HTML body. A failure is logged; for important emails, store a "to send" record in the same transaction and let a retrying job deliver it, the transactional outbox idea. See also application events and async processing.

6. Testing Locally with Mailpit

A mail catcher is a fake SMTP server that accepts every email and shows it in a web UI instead of delivering it. Mailpit is a popular one. Run it with Docker and point the application at it in the dev profile:

Terminal
docker run -d --name mailpit -p 1025:1025 -p 8025:8025 axllent/mailpit
application-dev.properties
spring.mail.host=localhost
spring.mail.port=1025
spring.mail.properties.mail.smtp.auth=false
spring.mail.properties.mail.smtp.starttls.enable=false

Place an order, then open http://localhost:8025 to see the email, with its HTML and plain-text parts and attachments. No real customer can receive it.

Console
Confirmation for order ORD-48213 sent to asha@example.com

7. Automated Tests

Unit-test the mailer with a mocked JavaMailSender and check the message it builds. A real MimeMessage is created from a Jakarta Mail session, so the content can be inspected:

OrderConfirmationMailerTest.java
package com.javabytechie.shop.mail;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import com.javabytechie.shop.order.OrderPlaced;
import jakarta.mail.Session;
import jakarta.mail.internet.MimeMessage;
import java.math.BigDecimal;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.mail.javamail.JavaMailSender;

class OrderConfirmationMailerTest {

    @Test
    void sendsOneConfirmationToTheCustomer() throws Exception {
        JavaMailSender sender = mock(JavaMailSender.class);
        when(sender.createMimeMessage()).thenReturn(new MimeMessage(Session.getInstance(new Properties())));
        OrderConfirmationMailer mailer = new OrderConfirmationMailer(sender, "orders@shop.example.com");

        mailer.onOrderPlaced(new OrderPlaced("ORD-1", "asha@example.com", "Asha", new BigDecimal("79.99")));

        ArgumentCaptor<MimeMessage> sent = ArgumentCaptor.forClass(MimeMessage.class);
        verify(sender).send(sent.capture());
        assertThat(sent.getValue().getSubject()).isEqualTo("Order ORD-1 confirmed");
        assertThat(sent.getValue().getAllRecipients()[0].toString()).isEqualTo("asha@example.com");
    }
}

For end-to-end tests, run Mailpit or GreenMail with Testcontainers and assert through their APIs that the email arrived.

8. Common Problems and Fixes

ProblemCauseFix
No JavaMailSender beanspring.mail.host is not setSet the host (and starter dependency)
MailAuthenticationExceptionWrong credentials, or the provider requires an app password or API keyUse the provider's SMTP credentials
Request hangs for minutesNo SMTP timeouts and an unreachable serverSet connection, read and write timeouts; send asynchronously
Email sent for an order that was rolled backSent inside the transactionUse @TransactionalEventListener or an outbox
Emails land in spamSender domain not authenticatedConfigure SPF, DKIM and DMARC for the sending domain with your provider
Garbled charactersWrong encodingUse UTF-8 in MimeMessageHelper

9. Best Practices

  • Send after commit and off the request thread, with @TransactionalEventListener and @Async, or an outbox for critical emails.
  • Always configure SMTP timeouts.
  • Keep SMTP credentials in secrets, never in application.properties.
  • Send both HTML and plain text, and escape user data in HTML.
  • Use a mail catcher in development so test emails never reach real people.
  • Use a transactional email provider with an authenticated domain for production delivery.

10. Summary

Sending email with Spring Boot needs spring-boot-starter-mail and spring.mail.* properties, after which the auto-configured JavaMailSender sends SimpleMailMessage text emails or MimeMessage emails built with MimeMessageHelper for HTML and attachments. Send business emails from an @Async @TransactionalEventListener so they leave only after a successful commit and never block requests, set SMTP timeouts, keep credentials secret, and use Mailpit locally and mocks or containers in tests.

11. References