Sending Emails in Spring Boot 4: SMTP, HTML Templates, Attachments and Testing
Send email from Spring Boot 4.1.2 with JavaMailSender: HTML and Thymeleaf templates, inline images, attachments, STARTTLS, timeouts, @Async and transactions, every result run against GreenMail.
You added spring-boot-starter-mail, pasted in your SMTP settings, and the first test message arrived. That is the easy ten percent. The other ninety is what this post is about: the signup request that hangs indefinitely because the mail server never answers, the “Welcome” email that goes out for an order that then rolls back, the subject line that turns into question marks, the HTML email whose logo shows up as an attachment.
Everything below was run, not recalled. A small module in the companion repository sends each kind of message to a GreenMail server running inside the test JVM, and every result quoted here is copied from a file that test run wrote. Where I am quoting documentation instead of output, I say so.
Tested against: Spring Boot 4.1.2 (the newest GA on Maven Central on 18 November 2026; Boot 4.1.0 was released on 10 June 2026 and 4.2.0-RC2 is a release candidate), Spring Framework 7.0.10, Jakarta Mail API 2.1.5 with Angus Mail 2.0.5, Thymeleaf 3.1.5, GreenMail 2.1.15, JDK 25 (Temurin 25.0.5). This is a rewrite of the Spring Boot 3 version of this guide: its “approximate” benchmark table is gone, replaced by numbers the module measures. Code and output: the email module of the companion repository.
Sending an email is handing a message to an SMTP server, nothing more
Your application does not deliver email. It opens a connection to an SMTP server, says who the message is from and who it is for, hands over the content and hangs up. The server does the delivering, later, and may refuse. So “sent” in your code means “the SMTP server accepted it”, and that is all it ever means.
Three pieces sit in your process. JavaMailSender is Spring’s interface, the one you inject. jakarta.mail is the API underneath it. Angus Mail is the library that implements that API and actually speaks SMTP. Spring Boot builds the JavaMailSender for you from spring.mail.* properties, and the figure shows where each of the three failures you will meet comes from.
The only dependency is the starter, shown here as it appears in the module’s pom.xml, next to the application.yml that configures it:
spring:
mail:
host: localhost # overridden by the tests; use your provider's SMTP host
port: 587
username: ${MAIL_USERNAME:}
password: ${MAIL_PASSWORD:}
properties:
"[mail.smtp.auth]": true
# enable=true upgrades to TLS only if the server offers it; required=true refuses to log in without it.
# See StartTlsTest and output/09-starttls.txt.
"[mail.smtp.starttls.enable]": true
"[mail.smtp.starttls.required]": true
# JavaMail's default for all three timeouts is "infinite". Set them. See FailureModesTest.
"[mail.smtp.connectiontimeout]": 5000
"[mail.smtp.timeout]": 10000
"[mail.smtp.writetimeout]": 10000
app:
mail:
from: [email protected]
Pro Tip: Avoid hardcoding credentials in your configuration file. For production, use environment variables or a configuration server like Spring Cloud Config to manage sensitive data securely. The placeholders above read environment variables, so the secret never enters the repository.
The keys that matter are host, port, username and password, plus whatever you put under properties, which is passed straight to Jakarta Mail as mail.smtp.* settings. The credentials come from environment variables, so nothing secret is in the file. The timeout and STARTTLS lines get their own sections below, because each one fixes a failure you will otherwise discover in production.
To see what Boot made of such settings, the test AutoConfigurationTest builds a context with a handful of them and prints the resulting bean (transcript 07-autoconfiguration.txt):
Two things to notice. spring.mail.ssl.enabled=true became mail.smtp.ssl.enable=trueandmail.smtp.ssl.checkserveridentity=true, so the certificate’s host name is checked by default. And defaultEncoding is UTF-8, which is also the property’s default and matters in a later section.
No spring.mail.host, no JavaMailSender. The auto-configuration is conditional on the host (or a JNDI name). Without either, nothing registers a sender, and any class that asks for one stops the application at startup. Transcript 10-no-mail-host.txt is the real console output of this module started without a host:
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.ankurm.email.MailService required a bean of type 'org.springframework.mail.javamail.JavaMailSender' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.mail.javamail.JavaMailSender' in your configuration.
Going deeper: what the Boot 4.1.2 mail starter actually contains
spring-boot-starter-mail brings in spring-boot-mail, a module of its own in Boot 4, whose auto-configuration classes live in the package org.springframework.boot.mail.autoconfigure. The dependency tree (mvn dependency:tree) shows jakarta.mail-api 2.1.5 at compile scope and angus-mail 2.0.5 at runtime scope: your code can import jakarta.mail.*, but the SMTP implementation is only on the runtime classpath.
spring-boot-starter-mail-test exists, but its pom contains only the mail starter and the general test starter. Nothing mail-specific, which is why this module uses GreenMail instead.
The properties Boot declares for the spring.mail prefix in 4.1.2, read from the jar’s configuration metadata: host, port, username, password, protocol (default smtp), default-encoding (default UTF-8), properties, jndi-name, test-connection (default false), and ssl.enabled (default false), ssl.bundle, ssl.verify-hostname (default true). A mail health indicator is controlled by management.health.mail.enabled, default true.
Boot ships a failure analyzer for exactly this situation, NoSuchMailSenderBeanFailureAnalyzer, whose message names spring.mail.host. In the run above the generic “consider defining a bean” message was printed instead; I did not investigate why.
Spring Framework’s own email chapter documents JavaMailSender, MimeMessageHelper and the exception hierarchy.
The smallest thing that works: a plain-text message
SimpleMailMessage is the postcard: a from, a to, a subject and a text body. This is sendPlain from MailService.java:
/** Shape 1: {@link SimpleMailMessage}. Text only, no attachments, no HTML. */
public void sendPlain(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(text);
sender.send(message);
}
To check it without a real mail server, the tests use GreenMail, an SMTP server that runs inside the test JVM and keeps what it receives in memory. The setup, from MimeStructureTest.java:
withPerMethodLifecycle(false) is not optional here. By default GreenMailExtension starts and stops the server around each test method. Spring builds the application context before the first method runs, so the @DynamicPropertySource that reads the server’s port finds no server yet, and the context fails to load. This cost one failed run while writing the module; the fix is the one call in the snippet above, which starts the server once per class.
With the server up, the first transcript line is the message as GreenMail received it (01-mime-structure.txt):
Every test class in the module registers its own GreenMail on a dynamic port (ServerSetupTest.SMTP.dynamicPort()), so classes do not share state. The tests read the received MimeMessage back and assert on it, and the same test writes the transcript, so a number in this post is an assertion in the build.
GreenMail also serves IMAP and POP3 if you want to read the mailbox the way a mail client would; this module only uses its SMTP side. See the GreenMail documentation.
If your tests must not touch any mail server at all, a mocked JavaMailSender works too, but then nothing checks the MIME structure, which is where the next section’s bugs live.
HTML, an inline logo and a PDF: one message is a tree of envelopes
As soon as a message has HTML, a plain-text fallback, an image and an attachment it is no longer one body but a tree, in a format called MIME. Each container says how to treat its children: multipart/alternative means “pick one of these, they say the same thing”, multipart/related means “these belong to the HTML”, and multipart/mixed means “all of these, in order”. The figure is the welcome email this module sends.
Spring’s MimeMessageHelper builds that tree for you. This is buildWelcome from MailService.java:
public MimeMessage buildWelcome(String to, String name, boolean withInline, boolean withAttachment)
throws MessagingException {
Context context = new Context();
context.setVariable("name", name);
String html = templates.process("mail/welcome.html", context);
String text = templates.process("mail/welcome.txt", context);
MimeMessage message = sender.createMimeMessage();
// true = multipart. Spring's default multipart mode for "true" is MULTIPART_MODE_MIXED_RELATED.
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject("Welcome, " + name);
helper.setText(text, html); // plain first, HTML second
if (withInline) {
helper.addInline("logo", new ClassPathResource("static/logo.png")); // AFTER setText
}
if (withAttachment) {
helper.addAttachment("welcome-guide.pdf",
new ByteArrayResource(Pdfs.tiny()), "application/pdf");
}
return message;
}
And this is the tree GreenMail received for it, printed by the test (first block of 01-mime-structure.txt for this message):
== 3. welcome: text + HTML + inline logo + PDF attachment
multipart/mixed
multipart/related
multipart/alternative
text/plain; charset=UTF-8
text/html;charset=UTF-8
image/png; name=inline [inline; filename=inline] [Content-ID <logo>]
application/pdf; name=welcome-guide.pdf [attachment; filename=welcome-guide.pdf]
The true in new MimeMessageHelper(message, true) means “multipart”, and Spring’s constant for it is MULTIPART_MODE_MIXED_RELATED. You pay for the nesting even when you attach nothing: the same call with no logo and no PDF still produces three levels (case 4 in the same transcript):
== 4. welcome without inline image and without attachment (helper still in multipart mode)
multipart/mixed
multipart/related
multipart/alternative
text/plain; charset=UTF-8
text/html;charset=UTF-8
Add the inline image after setText, not before. Calling addInline first raises no error. The image simply becomes the first part of multipart/related, ahead of the HTML (case 5 of the transcript):
RFC 2387 says the first part of a multipart/related is the root document unless a start parameter says otherwise, so some clients will treat your logo as the message. Put setText first, as the method above does.
Attachments need a multipart helper. A helper built with multipart=false throws as soon as you ask it for an attachment, with a message that tells you the fix (case 6 of 01-mime-structure.txt):
== 6. addAttachment on a helper built with multipart=false
IllegalStateException: Not in multipart mode - create an appropriate MimeMessageHelper via a constructor that takes a 'multipart' flag if you need to set alternative texts or add inline elements or attachments.
Going deeper: structure details worth knowing
An HTML-only message built with new MimeMessageHelper(message, false) and setText(html, true) is a single text/html part with no plain-text alternative (case 2 of the transcript). That is legal and common, and a client that prefers text has nothing to show; setText(plain, html) is what produces the multipart/alternative.
In the transcript the inline image part carries name=inline and filename=inline, the literal string, while the Content-ID is the <logo> you passed. The HTML refers to the image as cid:logo, which is the template line in the next section.
The PDF is a tiny one-page file generated in Pdfs.java so the attachment needs no bundled file.
Case 1 shows that SimpleMailMessage gives text/plain; charset=UTF-8: Boot’s default-encoding is applied even to the simplest message.
Templates: build the HTML with Thymeleaf, and know its two quiet traps
Concatenating HTML in Java is how you end up with a name containing an ampersand breaking your markup. Spring Boot already configures Thymeleaf, so the template is an ordinary file under templates/. These are the HTML and plain-text bodies of the welcome email (welcome.html and welcome.txt):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body style="font-family: Arial, sans-serif;">
<img src="cid:logo" alt="logo" width="48" height="48">
<h1>Welcome, <span th:text="${name}">Friend</span></h1>
<p>Your account is ready. The attached PDF has the short version of how to get started.</p>
</body>
</html>
Welcome, [(${name})]
Your account is ready. The attached PDF has the short version of how to get started.
Boot registers one template resolver, and it is in HTML mode. A .txt body needs TEXT mode, so MailTemplateConfig.java adds a second resolver that claims only *.txt:
== template resolvers on the engine (class, order, resolvable patterns)
ClassLoaderTemplateResolver order=0 patterns=[*.txt]
SpringResourceTemplateResolver order=null patterns=[]
[[…]] still HTML-escapes in a plain-text template. In TEXT mode the unescaped form is [(…)]. Both render the same hostile name below; welcome.txt uses the unescaped one, and a template written with the escaped form would put < and & into a message that is supposed to be plain text:
== name = <b>Evil</b> & Co
th:text -> <h1>Welcome, <span><b>Evil</b> & Co</span></h1>
th:utext -> <p><b>Evil</b> & Co</p>
[(...)] in TEXT mode -> Welcome, <b>Evil</b> & Co
[[...]] in TEXT mode -> Hello, <b>Evil</b> & Co
The same transcript shows the second trap, which is about typos. Misspell a top-level variable and Thymeleaf renders an empty string without a word; misspell a property of an object you did pass and it throws. A subject line reading “Hello, !” is how the first kind reaches production (same transcript, 02-templates.txt):
== a typo in a top-level variable name: ${nme} instead of ${name}
<p>Hello, <span></span>!</p>
== a typo in a property of an object you did pass: ${user.nmae}
TemplateProcessingException
root cause: EL1008E: Property or field 'nmae' cannot be found on object of type 'com.ankurm.email.TemplateTest$User' - maybe not public or not valid?
Going deeper: templates
th:text escapes and th:utext does not; the transcript shows <b>Evil</b> & Co coming out as markup with th:utext. Use th:utext only for HTML you wrote yourself, never for a user’s name.
spring.thymeleaf.cache defaults to true (read from the jar’s metadata), so the Spring Boot 3 version of this post’s advice to “enable template caching” describes what you already have. Turn it off in development only.
The module renders with Thymeleaf’s TemplateEngine directly, through MailService.render in MailService.java, so the same code can render without sending anything, which is how the template tests work.
Thymeleaf is also the engine behind the Thymeleaf and htmx CRUD UI post, and the PDF invoice post renders an invoice from a template the same way, which is a good source for the PDF you attach.
Non-English text works, until a setting makes it silently stop working
Email headers are 7-bit ASCII by specification, so a subject or a display name with other characters is wrapped in an “encoded word”: =?UTF-8?B?…?=, the character set and base64 in a row. Jakarta Mail does this for you, using the encoding Boot configured. The test EncodingTest sends a Devanagari subject, display name and body and reads them back (03-encoding.txt):
== default encoding (spring.mail.default-encoding = UTF-8)
raw Subject : =?UTF-8?B?4KS44KWN4KS14KS+4KSX4KSkIOCkueCliCwg4KSG4KS24KS+?=
raw To : =?UTF-8?B?4KSG4KS24KS+IOCkpuClh+CktuCkruClgeCklg==?= <[email protected]>
decoded : स्वागत है, आशा | To name: आशा देशमुख
body CTE : base64
body : आपका खाता तैयार है।
The header is the encoded word, the body is base64, and the decoded values are the originals. Now the failure: the same message through a JavaMailSenderImpl whose defaultEncoding is ISO-8859-1, which is what an old copied configuration might still say:
== a JavaMailSenderImpl whose defaultEncoding is ISO-8859-1
raw Subject : =?ISO-8859-1?B?Pz8/Pz8/ID8/LCA/Pz8=?=
decoded : ?????? ??, ???
body : ???? ???? ????? ???
Every character became a literal ? before it was encoded, and nothing threw. Leave spring.mail.default-encoding alone (it is UTF-8), and if you ever see question marks in a received subject, check this setting before anything else.
Going deeper: encoding
The transcript prints the raw header as the received server stored it, which is why you can see the =?ISO-8859-1?B?…?= wrapper even for the corrupted message: the charset label is honest, the content was already gone.
Display names with non-ASCII letters go through new InternetAddress(address, personal, "UTF-8") in sendInternational (MailService.java); the first transcript line labelled raw To is that name encoded.
For site-wide language handling of the content, see the Spring Boot 4 internationalization post; a MessageSource can feed a Thymeleaf template the same way it feeds a web page.
Talking to a real SMTP server: ports, TLS and the one setting that does not enforce it
A real provider asks for four things: host, port, user name and password, plus encryption. Two ports are in use. Port 465 starts encrypted (“implicit TLS”); port 587 starts in plain text and upgrades with a STARTTLS command. RFC 8314 recommends implicit TLS on 465 for mail submission, and says 587 with STARTTLS is acceptable as long as TLS is required. That last word is the whole section.
Jakarta Mail has two switches for 587. starttls.enable=true means “use STARTTLS if the server offers it”. starttls.required=true means “refuse to continue without it”. The test StartTlsTest points both settings at a server that does not offer STARTTLS, with a recording proxy in front of it (09-starttls.txt):
== mail.smtp.starttls.enable=true, server does not advertise STARTTLS
delivered: 1 message, no error
client sent: AUTH LOGIN
client sent: YWxpY2U= (base64 of the user name: alice)
client sent: czNjcmV0 (base64 of the password: s3cret)
== mail.smtp.starttls.required=true, same server
org.springframework.mail.MailSendException: Mail server connection failed. Failed messages: jakarta.mail.MessagingException: STARTTLS is required but host does not support STARTTLS
jakarta.mail.MessagingException: STARTTLS is required but host does not support STARTTLS
AUTH line sent: false
With only enable, the send succeeds without any error, and the proxy captured the user name and password crossing the wire as base64, which is an encoding and not encryption. With required, the send fails before any AUTH line is sent. The module’s application.yml above sets both for that reason.
A downgrade is silent. Anything between you and the server that strips the STARTTLS offer turns enable=true into a plain-text login, and your logs show a success. Use starttls.required=true on 587, or use 465 with spring.mail.ssl.enabled=true.
Gmail is the usual first provider. Per Google’s documentation it is smtp.gmail.com on 587 (STARTTLS) or 465 (SSL), and you authenticate with either an app password (which needs 2-Step Verification turned on) or OAuth 2. The old “Less secure app access” switch the Spring Boot 3 version of this post mentioned has been retired and no longer exists. For OAuth 2, the Angus Mail documentation says to set mail.smtp.auth.mechanisms=XOAUTH2 and pass the access token as the password; see its OAuth2 page. I did not run against Gmail, since that needs an account; everything here about Gmail is from those documents, not from a captured run.
Going deeper: getting mail accepted, not just sent
Google’s email sender guidelines require SPF or DKIM for every sender, and SPF, DKIM and DMARC for bulk senders (more than 5,000 messages a day to Gmail addresses, in force since 1 February 2024), and TLS for the connection. These are DNS records on your domain, not code, and without them a correct send can still land in spam.
Use a dedicated transactional provider (an SMTP relay you pay for) for anything customers depend on, and give it a sender address on a domain you control. The app.mail.from property in the module is where that address lives.
Use spring.mail.test-connection=true to make Boot open a connection at startup and fail fast on a bad host or credentials; its default is false.
The failure that hangs your request thread: timeouts
Four things go wrong when you send, and three of them fail fast with a clear exception. FailureModesTest provokes each against GreenMail or a deliberately broken server (06-failure-modes.txt):
== wrong password
org.springframework.mail.MailAuthenticationException: Authentication failed
jakarta.mail.AuthenticationFailedException: 535 5.7.8 Authentication credentials invalid
== right password
delivered: 1 message
== nothing listening on the port
org.springframework.mail.MailSendException
org.springframework.mail.MailSendException: Mail server connection failed. Failed messages: org.eclipse.angus.mail.util.MailConnectException: Couldn't connect to host, port: 127.0.0.1, 32877; timeout -1;
org.eclipse.angus.mail.util.MailConnectException: Couldn't connect to host, port: 127.0.0.1, 32877; timeout -1
java.net.ConnectException: Connection refused
== recipient that is not an address: 'not an address'
org.springframework.mail.MailParseException
org.springframework.mail.MailParseException: Could not parse mail
jakarta.mail.internet.AddressException: Local address contains control or whitespace
Read each one against the first figure. A bad address is a MailParseException before the network is touched, a refused connection is a MailSendException whose cause is the ConnectException, and a wrong password is a MailAuthenticationException. The numbers in the connection message vary per run; note timeout -1 in it, which is Angus saying that no connect timeout was configured.
The fourth case is the one that matters. The test starts a server that accepts the TCP connection and then never says anything, which is what an overloaded or firewalled mail server looks like (same transcript, 06-failure-modes.txt):
== server accepts the TCP connection and never sends the SMTP greeting
no timeouts set -> still blocked after 3000 ms; the caller is stuck
(after the connection was dropped: MailSendException)
mail.smtp.connectiontimeout=500 -> still blocked after 3000 ms; the caller is stuck
(after the connection was dropped: MailSendException)
mail.smtp.timeout=500 -> failed after ~500 ms
org.springframework.mail.MailSendException: Mail server connection failed. Failed messages: jakarta.mail.MessagingException: Exception reading response;
jakarta.mail.MessagingException: Exception reading response
java.net.SocketTimeoutException: Read timed out
With no timeouts the caller was still blocked when the test gave up at three seconds, and so was the run with only mail.smtp.connectiontimeout, because that setting limits opening the connection and this server opened it. Only mail.smtp.timeout, the socket read timeout, ended the wait. Set all three in your application.yml, as the module does: connectiontimeout, timeout and writetimeout.
No timeout means an unbounded wait. A signup endpoint that sends a welcome email on the request thread will hold that thread, and a database connection if one is open, for as long as the server stays silent. Under load that is an outage with no error in the logs.
A quick reference for the symptoms, kept from the earlier version of this post and corrected where the measurements disagreed:
Symptom
Usual cause
What to check
MailAuthenticationException
Wrong user or password, or an account that needs an app password or OAuth 2
Credentials from the environment; provider’s documentation
MailSendException with ConnectException
Wrong host or port, or a firewall
spring.mail.host, spring.mail.port
MailParseException
Malformed address or header
Validate the address before building the message
Request never returns
No read timeout
mail.smtp.timeout and friends
Question marks in non-English text
Wrong default-encoding
Leave it at UTF-8
Login worked but nothing arrives
Message accepted, then filtered
SPF, DKIM, DMARC; spam folder
Going deeper: reading the exceptions
All three Spring exceptions extend MailException, which is unchecked, so a failure does not force a try; it also means nothing forces you to handle it. The original Jakarta Mail exception is always the cause, as the indented lines in the transcript show.
The transcript lines starting with two spaces are the chain of causes, outermost first, printed by the test, so you can match them against your own stack traces.
Doing it off the request thread, and what really costs time: connections
The obvious fix for a slow send is @Async. It helps, but it changes what you can know, and a second, quieter cost is how many connections you open. Both are measured in AsyncAndConnectionsTest, with a proxy that adds 50 ms of simulated latency to every server reply (04-async-and-connections.txt):
simulated SMTP latency: 50 ms per server reply; 5 messages
send(message) once per message : 5 connections, 2083 ms
send(message...) varargs : 1 connection, 1449 ms
@Async sendWelcome x5 : caller resumed after 9 ms, all delivered after 444 ms, 5 connections
Each send(message) call opens a connection, does the SMTP conversation and closes it, so five calls cost five connections. The varargs overload send(MimeMessage...) sends them over one connection. This is the correction to the Spring Boot 3 version of this post, which suggested that mail.smtp.connectiontimeout was “connection pooling”: it is a timeout, and there is no pool. The two methods, from MailService.java:
public void sendBatch(MimeMessage... messages) {
sender.send(messages);
}
/** Same loop with one {@code send(...)} per message: one connection each. */
public void sendOneByOne(MimeMessage... messages) {
for (MimeMessage message : messages) {
sender.send(message);
}
}
The @Async run was fastest at 444 ms because five threads each opened a connection in parallel, and the caller resumed after 9 ms. Which service does that? AsyncMailService.java has two flavours:
@Async
public void sendWelcomeFireAndForget(String to, String name) throws MessagingException {
mail.sendWelcome(to, name);
}
/**
* CompletableFuture: same hand-off, but the caller can attach a handler or wait for the outcome. The result is
* the name of the thread that did the sending, so the transcript can show it was not the caller's.
*/
@Async
public CompletableFuture<String> sendWelcome(String to, String name) {
try {
mail.sendWelcome(to, name);
return CompletableFuture.completedFuture(Thread.currentThread().getName());
} catch (MessagingException | RuntimeException e) {
return CompletableFuture.failedFuture(e);
}
}
The first returns void. If sending fails, the caller never finds out. The second returns a CompletableFuture, which carries the failure. The test sends both to an invalid address (05-async-failures.txt):
== void @Async, recipient 'not an address'
caller: returned normally, no exception
logged: [ERROR] Unexpected exception occurred invoking async method: public void com.ankurm.email.AsyncMailService.sendWelcomeFireAndForget(java.lang.String,java.lang.String) throws jakarta.mail.MessagingException
exception: jakarta.mail.internet.AddressException
== CompletableFuture<String> @Async, same recipient
future.get() threw ExecutionException
cause: jakarta.mail.internet.AddressException: Local address contains control or whitespace
A void @Async email can fail with nobody told. The caller returned normally. The only trace was a log line from Spring’s default handler. If the email matters, return a CompletableFuture and handle it, or hand the job to a queue that retries.
Retries, scheduling and surviving a restart are the job of a persistent queue; see background jobs with JobRunr. I did not wire JobRunr to mail in this module.
Send a welcome email twice and the customer gets two. If a retry can repeat a send, the idempotency keys post describes how to make the repeat harmless; again, not demonstrated here.
Email and database transactions: do not send until you have committed
A common method looks like this: save the order, send the confirmation, and if something later fails the transaction rolls back. The database forgets the order. The email is already gone. The test TransactionTest runs the same business rule written two ways and counts the emails that arrive (08-transactions.txt):
send inside the transaction, then roll back : 1 email delivered
AFTER_COMMIT listener, then roll back : 0 emails delivered
AFTER_COMMIT listener, commit : 1 email delivered
The first design, from OrderService.java, sends directly inside the transactional method:
@Transactional
public void placeOrderMailInside(String to, boolean fail) {
mail.sendPlain(to, "Order confirmed", "Thanks for your order.");
if (fail) {
throw new IllegalStateException("payment declined");
}
}
The second publishes an event, and a listener sends it only after the commit (OrderMailListener.java):
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
void onOrderPlaced(OrderPlaced event) {
mail.sendPlain(event.customerEmail(), "Order confirmed", "Thanks for your order.");
}
The rollback produces zero emails and the commit produces one. The test uses a no-op transaction manager, so the transaction behaviour is real Spring and the database is not part of the demonstration.
The trade-off is the reverse failure. After the commit, the send can fail and the order stays committed with no email. That is usually the better of the two outcomes, but it means the failure needs a retry or an alert. A durable outbox table written in the same transaction closes the gap; this module does not implement one.
Going deeper: after-commit details
The listener runs after the commit, on the thread that committed. If it should not delay the response, make it asynchronous as in the previous section; if it must survive a crash between commit and send, you need the outbox.
Without an active transaction, a @TransactionalEventListener is silently skipped unless fallbackExecution = true is set. The test runs inside a transaction, so this is documented behaviour in the Spring Framework reference and not something the module exercises.
Should your application send email itself at all?
Often, no. Sending a handful of transactional messages from your own process is fine. Once volume, deliverability or retries matter, a provider’s API, or a queue in front of the SMTP call, is the better place for the problem to live. Everything in this post still applies inside that service: the timeouts, the TLS setting, the encoding and the commit ordering are properties of any code that sends mail.
A production checklist, each item backed by a section above
Set mail.smtp.connectiontimeout, timeout and writetimeout (section on timeouts).
Set starttls.required=true on 587, or use 465 with SSL enabled (TLS section).
Take credentials from the environment, never the file.
Leave default-encoding at UTF-8 (encoding section).
Add inline images after setText (MIME section).
Send after the commit, not inside the transaction (transactions section).
Use the varargs send for batches, and return a CompletableFuture from async senders.
Publish SPF, DKIM and DMARC for your sending domain.
Further reading
Companion code and every transcript quoted above: the email module of the spring-boot-demo repository, and its README.
No Comments yet!