Sending Email with Spring Boot
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.
2. Dependency and SMTP Configuration
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
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>
| Property | Meaning |
|---|---|
spring.mail.host, spring.mail.port | SMTP server; port 587 with STARTTLS is the usual choice for submission |
spring.mail.username, spring.mail.password | Credentials; 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-encoding | Message encoding, UTF-8 by default |
spring.mail.test-connection | Check 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
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.
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
package com.javabytechie.shop.order;
import java.math.BigDecimal;
public record OrderPlaced(String orderId, String customerEmail, String customerName, BigDecimal total) {
}
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
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
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:
docker run -d --name mailpit -p 1025:1025 -p 8025:8025 axllent/mailpit
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.
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:
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
| Problem | Cause | Fix |
|---|---|---|
No JavaMailSender bean | spring.mail.host is not set | Set the host (and starter dependency) |
MailAuthenticationException | Wrong credentials, or the provider requires an app password or API key | Use the provider's SMTP credentials |
| Request hangs for minutes | No SMTP timeouts and an unreachable server | Set connection, read and write timeouts; send asynchronously |
| Email sent for an order that was rolled back | Sent inside the transaction | Use @TransactionalEventListener or an outbox |
| Emails land in spam | Sender domain not authenticated | Configure SPF, DKIM and DMARC for the sending domain with your provider |
| Garbled characters | Wrong encoding | Use UTF-8 in MimeMessageHelper |
9. Best Practices
- Send after commit and off the request thread, with
@TransactionalEventListenerand@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
Sending Email with Spring Boot Interview Questions and Answers
Common interview questions on Sending Email with Spring Boot, from basic to scenario-based, with short answers you can explain in your own words.
Q. How do you send email in a Spring Boot application?
Answer: Add spring-boot-starter-mail, configure the SMTP server with spring.mail.host, port, credentials and Jakarta Mail properties, and inject the auto-configured JavaMailSender. Send a SimpleMailMessage for plain text or build a MimeMessage with MimeMessageHelper for HTML and attachments. The bean is only created when spring.mail.host is set.
Q. What is the difference between SimpleMailMessage and MimeMessage?
Answer: SimpleMailMessage is a simple Spring value object for plain-text emails with from, to, subject and text. MimeMessage is the Jakarta Mail type for full MIME messages: HTML bodies, alternative text and HTML parts, inline images and attachments. MimeMessageHelper makes building it easier; multipart mode must be enabled for attachments.
Q. Why should an order confirmation email not be sent inside the @Transactional method that saves the order?
Answer: If the transaction rolls back after the email is sent, the customer receives a confirmation for an order that does not exist, and a slow SMTP server keeps the transaction and its database connection open. Publish an event and send from a @TransactionalEventListener, which runs after commit, ideally with @Async. For guaranteed delivery, use a transactional outbox.
Q. How do you test email sending without emailing real users?
Answer: In unit tests, mock JavaMailSender and capture the message to check recipients, subject and body. In local development and integration tests, point spring.mail.host at a mail catcher such as Mailpit or GreenMail, often started with Docker or Testcontainers, which accepts all messages and exposes them in a UI or API.
Q. After deployment, password reset emails sometimes take several minutes and some requests time out. What would you check?
Answer: That SMTP connection, read and write timeouts are set, since Jakarta Mail waits indefinitely by default; that sending happens asynchronously rather than on the request thread; and the provider's rate limits and latency. Then add monitoring through the mail health indicator and logs, and consider a queue or outbox with retries so a slow provider never affects user requests.