Add email module: JavaMailSender on Spring Boot 4.1.2 / Jakarta Mail 2.1.5, tested against GreenMail with real transcripts

Nine tests, each writing a transcript to email/output/: the MIME tree for six message shapes (mixed > related >
alternative; addInline before setText puts the image first; addAttachment on a non-multipart helper throws),
Thymeleaf HTML and TEXT templates ([[...]] still HTML-escapes in TEXT mode, [(...)] does not), Devanagari subjects as
encoded-words and a wrong defaultEncoding turning them into '?', connections and latency through a delaying TCP proxy
(5 connections for one send per message, 1 for the varargs send, @Async returning in milliseconds), a void @Async
failure that never reaches the caller, a server that never sends the SMTP greeting blocking forever until
mail.smtp.timeout is set (connectiontimeout does not help), starttls.enable authenticating over plain text with the
base64 password captured on the wire while starttls.required refuses, spring.mail.* mapped onto JavaMailSenderImpl,
spring.mail.test-connection, and an email still sent when the transaction rolls back unless it waits for AFTER_COMMIT.

Found while writing: GreenMailExtension starts per test method by default, so a @DynamicPropertySource that reads its
port needs withPerMethodLifecycle(false).

No docs/ folder; the explanations live in the article's accordions.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b7SK2mvUEELeLtMi1o
This commit is contained in:
Claude
2026-11-18 21:17:37 +05:30
parent c9a2b766bb
commit da700a564f
44 changed files with 1638 additions and 0 deletions
+50
View File
@@ -0,0 +1,50 @@
# email
Companion code for **Sending Emails in Spring Boot 4: SMTP, HTML Templates, Attachments and Testing** on
[ankurm.com](https://ankurm.com/sending-emails-in-spring-boot-3-a-complete-guide/).
One `MailService` builds each message shape (plain text, HTML, a Thymeleaf HTML + text pair with an inline image and
a PDF attachment) and sends it through Spring Boot's auto-configured `JavaMailSender`. The tests send to a GreenMail
server running inside the JVM, read the result back, and write what they saw to `output/`. A small TCP proxy in front
of GreenMail adds latency and counts connections; a "black hole" server that never sends the SMTP greeting shows what
happens without timeouts.
| Piece | Version | Checked against |
|---|---|---|
| Spring Boot | 4.1.2 | `maven-metadata.xml` for `spring-boot-starter-parent` (4.2.0-RC2 exists but is not GA) |
| Spring Framework | 7.0.10 | `mvn dependency:tree` |
| Jakarta Mail API / Angus Mail | 2.1.5 / 2.0.5 (Angus is `runtime` scope) | `mvn dependency:tree` |
| Thymeleaf | 3.1.5.RELEASE (managed by Boot) | `mvn dependency:tree` |
| GreenMail | 2.1.15 | `maven-metadata.xml` |
| JDK | 25 | Temurin 25.0.5+8 |
## Run it
```bash
export JAVA_HOME=/path/to/jdk-25
mvn -B test # 9 tests, transcripts 01-09 written to output/
./scripts/run-all.sh # the above plus transcript 10 (the app without spring.mail.host) and the test summary
```
Nothing else is needed: no SMTP account, no Docker. To send real mail, set `spring.mail.host`, `port`, `username`
and `password` (see `src/main/resources/application.yml`; `MAIL_USERNAME` and `MAIL_PASSWORD` are read from the
environment) and call `MailService` from your own code. There is no web layer in this module.
## What is in `output/`
| File | What it shows |
|---|---|
| `01-mime-structure.txt` | the MIME tree for six ways of building a message, including `addInline` before `setText` and `addAttachment` on a non-multipart helper |
| `02-templates.txt` | the two Thymeleaf resolvers, `th:text` vs `th:utext`, `[(...)]` vs `[[...]]` in TEXT mode, a silent typo in a variable name vs a loud one in a property |
| `03-encoding.txt` | a Devanagari subject and display name as encoded-words on the wire, and a wrong `defaultEncoding` turning them into `?` |
| `04-async-and-connections.txt` | connections and time for one `send` per message, one varargs `send`, and `@Async`, with 50 ms of simulated SMTP latency (timings are indicative) |
| `05-async-failures.txt` | a `void @Async` failure that never reaches the caller, and the same failure through a `CompletableFuture` |
| `06-failure-modes.txt` | wrong password, closed port, bad address, and a server that never greets: blocked forever without `mail.smtp.timeout` (the port in this file changes per run) |
| `07-autoconfiguration.txt` | what `spring.mail.*` becomes on `JavaMailSenderImpl`, no `JavaMailSender` without a host, `spring.mail.test-connection` |
| `08-transactions.txt` | an email sent inside a transaction that rolls back, and the `AFTER_COMMIT` fix |
| `09-starttls.txt` | `starttls.enable` authenticating over plain text (the base64 password captured on the wire) vs `starttls.required` refusing |
| `10-no-mail-host.txt` | the console output when the app starts without `spring.mail.host` |
| `11-test-summary.txt` | the Maven test summary |
Transcripts 01-09 come out of the test suite, so each number in them is an assertion that fails the build when it
stops being true. Transcript 04's timings depend on the machine.
+30
View File
@@ -0,0 +1,30 @@
== 1. SimpleMailMessage (sendPlain)
text/plain; charset=UTF-8
== 2. HTML only, non-multipart helper (sendHtmlOnly)
text/html;charset=UTF-8
== 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]
== 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
== 5. addInline BEFORE setText
multipart/mixed
multipart/related
image/png; name=inline [inline; filename=inline] [Content-ID <logo>]
text/html;charset=UTF-8
== 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.
+22
View File
@@ -0,0 +1,22 @@
== template resolvers on the engine (class, order, resolvable patterns)
ClassLoaderTemplateResolver order=0 patterns=[*.txt]
SpringResourceTemplateResolver order=null patterns=[]
== welcome.html with name = Asha
<h1>Welcome, <span>Asha</span></h1>
== welcome.txt with name = Asha (TEXT mode)
Welcome, Asha
== name = <b>Evil</b> & Co
th:text -> <h1>Welcome, <span>&lt;b&gt;Evil&lt;/b&gt; &amp; Co</span></h1>
th:utext -> <p><b>Evil</b> & Co</p>
[(...)] in TEXT mode -> Welcome, <b>Evil</b> & Co
[[...]] in TEXT mode -> Hello, &lt;b&gt;Evil&lt;/b&gt; &amp; Co
== 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?
+11
View File
@@ -0,0 +1,11 @@
== 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 : आपका खाता तैयार है।
== a JavaMailSenderImpl whose defaultEncoding is ISO-8859-1
raw Subject : =?ISO-8859-1?B?Pz8/Pz8/ID8/LCA/Pz8=?=
decoded : ?????? ??, ???
body : ???? ???? ????? ???
@@ -0,0 +1,5 @@
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
ran on thread(s) : [task-3, task-4, task-5, task-6, task-7]
+8
View File
@@ -0,0 +1,8 @@
== 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
+27
View File
@@ -0,0 +1,27 @@
== 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
== 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
+19
View File
@@ -0,0 +1,19 @@
== spring.mail.host, port, username, default-encoding, ssl.enabled and two mail.* properties
bean : JavaMailSenderImpl
host / port : smtp.example.test / 2525
protocol : smtp
defaultEncoding : UTF-8
session props : {mail.smtp.auth=true, mail.smtp.ssl.checkserveridentity=true, mail.smtp.ssl.enable=true, mail.smtp.timeout=7000}
== no spring.mail.host
JavaMailSender bean present: false
== no spring.mail.host, and a bean that needs a JavaMailSender
No qualifying bean of type 'org.springframework.mail.javamail.JavaMailSender' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
== spring.mail.test-connection=true against a port nothing listens on
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.mail.autoconfigure.MailSenderValidatorAutoConfiguration': Failed to instantiate [org.springframework.boot.mail.autoconfigure.MailSenderValidatorAutoConfiguration]: Constructor threw exception
org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.mail.autoconfigure.MailSenderValidatorAutoConfiguration]: Constructor threw exception
java.lang.IllegalStateException: Mail server is not available
org.eclipse.angus.mail.util.MailConnectException: Couldn't connect to host, port: 127.0.0.1, 1; timeout -1
java.net.ConnectException: Connection refused
+3
View File
@@ -0,0 +1,3 @@
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
+10
View File
@@ -0,0 +1,10 @@
== 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
+12
View File
@@ -0,0 +1,12 @@
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.
+9
View File
@@ -0,0 +1,9 @@
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.013 s -- in com.ankurm.email.MimeStructureTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.410 s -- in com.ankurm.email.TransactionTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 6.727 s -- in com.ankurm.email.FailureModesTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.164 s -- in com.ankurm.email.StartTlsTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.389 s -- in com.ankurm.email.EncodingTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.289 s -- in com.ankurm.email.AsyncAndConnectionsTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.101 s -- in com.ankurm.email.AutoConfigurationTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.167 s -- in com.ankurm.email.TemplateTest
Tests run: 9, Failures: 0, Errors: 0, Skipped: 0
+71
View File
@@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.1.2</version>
<relativePath/>
</parent>
<groupId>com.ankurm</groupId>
<artifactId>email</artifactId>
<version>1.0.0</version>
<name>email</name>
<description>Sending email from Spring Boot 4.1: plain text, Thymeleaf HTML, inline images and attachments,
@Async, timeouts, failure modes and tests against GreenMail, with the MIME structure printed.</description>
<packaging>jar</packaging>
<properties>
<java.version>25</java.version>
<greenmail.version>2.1.15</greenmail.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- Transactions: you already have this if you use JPA or JDBC. Here it is explicit because the demo has no database. -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.icegreen</groupId>
<artifactId>greenmail-junit5</artifactId>
<version>${greenmail.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-Duser.timezone=UTC -Dfile.encoding=UTF-8</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
# Starts the real application with no spring.mail.host (application.yml is not read) and keeps the console output
# Spring Boot prints when it cannot start. Writes output/10-no-mail-host.txt.
set -uo pipefail
cd "$(dirname "$0")/.."
mkdir -p output
mvn -B -q -DskipTests package >/dev/null 2>&1 || { echo "build failed"; exit 1; }
java -jar target/email-1.0.0.jar --spring.config.location=optional:file:./does-not-exist.yml --spring.main.banner-mode=off \
2>&1 | sed -n '/APPLICATION FAILED TO START/,$p' | sed 's/\x1b\[[0-9;]*m//g' > output/10-no-mail-host.txt
cat output/10-no-mail-host.txt
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env bash
# Regenerates every file under output/.
#
# ./scripts/run-all.sh
#
# Needs JDK 25 and Maven 3.9. Nothing else: GreenMail runs inside the tests, and the "no mail host" failure comes
# from starting the packaged jar. Transcripts 01-09 come out of the test suite, so each line in them is an assertion
# that fails the build when it stops being true. Timings in 04 depend on the machine; ports in 06 change per run.
set -euo pipefail
cd "$(dirname "$0")/.."
mkdir -p output
echo "== test suite (transcripts 01-09)"
mvn -B test | tee /tmp/email-mvn.log | grep -E '^\[(INFO|WARNING|ERROR)\] Tests run:' | sed 's/^\[[A-Z]*\] //' > output/11-test-summary.txt
echo "== application without spring.mail.host (transcript 10)"
./scripts/no-mail-host.sh >/dev/null || true
echo
echo "output:"
ls -1 output
@@ -0,0 +1,41 @@
package com.ankurm.email;
import jakarta.mail.MessagingException;
import java.util.concurrent.CompletableFuture;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
/**
* Two ways to make sending asynchronous, and the difference that matters: what the caller can learn about a failure.
* This is a separate bean on purpose. {@code @Async} works through a proxy, so a call from {@link MailService} to
* its own method would run on the caller's thread (the self-invocation trap from the @Async article).
*/
@Service
public class AsyncMailService {
private final MailService mail;
public AsyncMailService(MailService mail) {
this.mail = mail;
}
/** void: the caller gets control back at once and can never find out whether the email was sent. */
@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);
}
}
}
@@ -0,0 +1,19 @@
package com.ankurm.email;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
/**
* Companion code for "Sending Emails in Spring Boot 4" on ankurm.com. There is no web layer on purpose: every
* behaviour in the article is something a service does with a {@code JavaMailSender}, and the tests call the
* service directly and read the result off a GreenMail server.
*/
@SpringBootApplication
@EnableAsync
public class EmailApplication {
public static void main(String[] args) {
SpringApplication.run(EmailApplication.class, args);
}
}
@@ -0,0 +1,119 @@
package com.ankurm.email;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
/**
* The synchronous sending code from the article: one method per message shape. Each method builds the message and
* hands it to {@link JavaMailSender}; nothing here is asynchronous (see {@link AsyncMailService}).
*/
@Service
public class MailService {
private final JavaMailSender sender;
private final TemplateEngine templates;
private final String from;
public MailService(JavaMailSender sender, TemplateEngine templates,
@Value("${app.mail.from:[email protected]}") String from) {
this.sender = sender;
this.templates = templates;
this.from = from;
}
/** 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);
}
/** Shape 2: HTML only. Not recommended: there is no plain-text alternative for clients that want one. */
public void sendHtmlOnly(String to, String subject, String html) throws MessagingException {
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, false);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(html, true);
sender.send(message);
}
/**
* Shape 3: the welcome email from the article. A Thymeleaf HTML body and a Thymeleaf plain-text body in one
* {@code multipart/alternative}, an inline logo referenced as {@code cid:logo}, and a PDF attachment.
*/
public void sendWelcome(String to, String name) throws MessagingException {
sender.send(buildWelcome(to, name, true, true));
}
/** Builds the welcome message without sending it, so tests can send several in one connection. */
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;
}
/** Sends several messages over ONE SMTP connection ({@code send(MimeMessage...)} varargs). */
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);
}
}
/** Non-ASCII display name + subject + body, to show how the headers are encoded on the wire. */
public void sendInternational(String to, String displayName, String subject, String body)
throws MessagingException, UnsupportedEncodingException {
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, false);
helper.setFrom(from);
helper.setTo(new jakarta.mail.internet.InternetAddress(to, displayName, "UTF-8"));
helper.setSubject(subject);
helper.setText(body, false);
sender.send(message);
}
/** Renders a template without sending anything. */
public String render(String template, Map<String, Object> variables) {
Context context = new Context();
variables.forEach(context::setVariable);
return templates.process(template, context);
}
}
@@ -0,0 +1,27 @@
package com.ankurm.email;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
/**
* Spring Boot configures one Thymeleaf resolver, in HTML mode. A plain-text body needs TEXT mode, otherwise
* {@code [[${name}]]} would be HTML-escaped and the template parsed as markup. This second resolver claims only
* {@code *.txt}; Boot's {@code SpringTemplateEngine} picks up every {@code ITemplateResolver} bean.
*/
@Configuration
public class MailTemplateConfig {
@Bean
ClassLoaderTemplateResolver textTemplateResolver() {
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
resolver.setPrefix("templates/");
resolver.setTemplateMode(TemplateMode.TEXT);
resolver.setCharacterEncoding("UTF-8");
resolver.setResolvablePatterns(java.util.Set.of("*.txt"));
resolver.setOrder(0);
resolver.setCheckExistence(true);
return resolver;
}
}
@@ -0,0 +1,21 @@
package com.ankurm.email;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;
/** Runs only if the publishing transaction committed. A rollback means the event is dropped and no email is sent. */
@Component
public class OrderMailListener {
private final MailService mail;
public OrderMailListener(MailService mail) {
this.mail = mail;
}
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
void onOrderPlaced(OrderPlaced event) {
mail.sendPlain(event.customerEmail(), "Order confirmed", "Thanks for your order.");
}
}
@@ -0,0 +1,5 @@
package com.ankurm.email;
/** Published when an order is placed; the confirmation email is sent only after the transaction commits. */
public record OrderPlaced(String customerEmail) {
}
@@ -0,0 +1,39 @@
package com.ankurm.email;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* The same business rule written two ways. Both throw "payment declined" after the email step when {@code fail} is
* true, so the transaction rolls back; only one of them has already sent the email by then.
*/
@Service
public class OrderService {
private final MailService mail;
private final ApplicationEventPublisher events;
public OrderService(MailService mail, ApplicationEventPublisher events) {
this.mail = mail;
this.events = events;
}
/** Sends inside the transaction: the email leaves before anyone knows whether the order will commit. */
@Transactional
public void placeOrderMailInside(String to, boolean fail) {
mail.sendPlain(to, "Order confirmed", "Thanks for your order.");
if (fail) {
throw new IllegalStateException("payment declined");
}
}
/** Publishes an event; {@link OrderMailListener} sends only AFTER_COMMIT. */
@Transactional
public void placeOrderMailAfterCommit(String to, boolean fail) {
events.publishEvent(new OrderPlaced(to));
if (fail) {
throw new IllegalStateException("payment declined");
}
}
}
@@ -0,0 +1,22 @@
package com.ankurm.email;
import java.nio.charset.StandardCharsets;
/** A byte-for-byte valid but tiny one-page PDF, so the attachment in the demo is a real PDF and not a text file. */
final class Pdfs {
private Pdfs() {
}
static byte[] tiny() {
String pdf = """
%PDF-1.4
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] >> endobj
trailer << /Root 1 0 R /Size 4 >>
%%EOF
""";
return pdf.getBytes(StandardCharsets.US_ASCII);
}
}
+20
View File
@@ -0,0 +1,20 @@
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]
Binary file not shown.

After

Width:  |  Height:  |  Size: 73 B

@@ -0,0 +1,8 @@
<!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>
@@ -0,0 +1,3 @@
Welcome, [(${name})]
Your account is ready. The attached PDF has the short version of how to get started.
@@ -0,0 +1,158 @@
package com.ankurm.email;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.awaitility.Awaitility.await;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import com.icegreen.greenmail.junit5.GreenMailExtension;
import com.icegreen.greenmail.util.ServerSetupTest;
import jakarta.mail.internet.MimeMessage;
import java.io.IOException;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
/**
* Connections, latency and failure visibility with a simulated 50 ms SMTP round trip (a proxy in front of GreenMail).
* Writes output/04-async-and-connections.txt. Timings are indicative: they depend on the machine.
*/
@SpringBootTest
class AsyncAndConnectionsTest {
static final int DELAY_MS = 50;
static final int MESSAGES = 5;
@RegisterExtension
static GreenMailExtension greenMail = new GreenMailExtension(ServerSetupTest.SMTP.dynamicPort()).withPerMethodLifecycle(false);
static SlowProxy proxy;
@BeforeAll
static void startProxy() throws IOException {
proxy = new SlowProxy(greenMail.getSmtp().getPort(), DELAY_MS);
}
@AfterAll
static void stopProxy() throws IOException {
proxy.close();
}
@DynamicPropertySource
static void mail(DynamicPropertyRegistry registry) {
registry.add("spring.mail.port", () -> proxy.port());
registry.add("spring.mail.properties.mail.smtp.auth", () -> "false");
registry.add("spring.mail.properties.mail.smtp.starttls.enable", () -> "false");
registry.add("spring.mail.properties.mail.smtp.starttls.required", () -> "false");
}
@Autowired MailService mail;
@Autowired AsyncMailService async;
@BeforeEach
void clean() throws Exception {
greenMail.purgeEmailFromAllMailboxes();
proxy.connections.set(0);
}
private MimeMessage[] build() throws Exception {
MimeMessage[] messages = new MimeMessage[MESSAGES];
for (int i = 0; i < MESSAGES; i++) {
messages[i] = mail.buildWelcome("user" + i + "@example.test", "User" + i, false, false);
}
return messages;
}
private static long since(long startNanos) {
return Duration.ofNanos(System.nanoTime() - startNanos).toMillis();
}
@Test
void connectionsAndLatency() throws Exception {
try (Transcript t = Transcript.open("04-async-and-connections.txt")) {
t.line("simulated SMTP latency: %d ms per server reply; %d messages", DELAY_MS, MESSAGES);
long start = System.nanoTime();
mail.sendOneByOne(build());
long oneByOne = since(start);
int oneByOneConnections = proxy.connections.get();
t.line("send(message) once per message : %d connections, %d ms", oneByOneConnections, oneByOne);
assertThat(greenMail.getReceivedMessages()).hasSize(MESSAGES);
assertThat(oneByOneConnections).isEqualTo(MESSAGES);
greenMail.purgeEmailFromAllMailboxes();
proxy.connections.set(0);
start = System.nanoTime();
mail.sendBatch(build());
long batch = since(start);
int batchConnections = proxy.connections.get();
t.line("send(message...) varargs : %d connection, %d ms", batchConnections, batch);
assertThat(greenMail.getReceivedMessages()).hasSize(MESSAGES);
assertThat(batchConnections).isEqualTo(1);
greenMail.purgeEmailFromAllMailboxes();
proxy.connections.set(0);
start = System.nanoTime();
List<CompletableFuture<String>> futures = IntStream.range(0, MESSAGES)
.mapToObj(i -> async.sendWelcome("user" + i + "@example.test", "User" + i)).toList();
long returned = since(start);
CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).get(30, TimeUnit.SECONDS);
long done = since(start);
t.line("@Async sendWelcome x%d : caller resumed after %d ms, all delivered after %d ms, %d connections",
MESSAGES, returned, done, proxy.connections.get());
t.line("ran on thread(s) : %s", futures.stream().map(f -> f.join()).distinct().toList());
assertThat(greenMail.getReceivedMessages()).hasSize(MESSAGES);
assertThat(returned).isLessThan(oneByOne / 5);
assertThat(futures.get(0).join()).isNotEqualTo(Thread.currentThread().getName());
}
}
@Test
void asyncFailuresAreInvisibleUnlessYouReturnAFuture() throws Exception {
try (Transcript t = Transcript.open("05-async-failures.txt")) {
Logger logger = (Logger) LoggerFactory.getLogger(SimpleAsyncUncaughtExceptionHandler.class);
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.start();
logger.addAppender(appender);
try {
t.line("== void @Async, recipient 'not an address'");
async.sendWelcomeFireAndForget("not an address", "X");
t.line("caller: returned normally, no exception");
await().atMost(Duration.ofSeconds(5)).until(() -> !appender.list.isEmpty());
ILoggingEvent event = appender.list.get(0);
t.line("logged: [%s] %s", event.getLevel(), event.getFormattedMessage());
t.line("exception: %s", event.getThrowableProxy().getClassName());
assertThat(greenMail.getReceivedMessages()).isEmpty();
} finally {
logger.detachAppender(appender);
}
t.line("");
t.line("== CompletableFuture<String> @Async, same recipient");
CompletableFuture<String> future = async.sendWelcome("not an address", "X");
assertThatThrownBy(future::get).isInstanceOf(ExecutionException.class);
try {
future.get();
} catch (ExecutionException e) {
t.line("future.get() threw ExecutionException");
t.line("cause: %s: %s", e.getCause().getClass().getName(), e.getCause().getMessage());
}
}
}
}
@@ -0,0 +1,76 @@
package com.ankurm.email;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Map;
import java.util.TreeMap;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.mail.autoconfigure.MailSenderAutoConfiguration;
import org.springframework.boot.mail.autoconfigure.MailSenderValidatorAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
/** What spring.mail.* turns into, and what happens without a host. Writes output/07-autoconfiguration.txt. */
class AutoConfigurationTest {
static class NeedsSender {
NeedsSender(JavaMailSender sender) {
}
}
private final ApplicationContextRunner runner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(MailSenderAutoConfiguration.class, MailSenderValidatorAutoConfiguration.class));
private static Throwable root(Throwable t) {
while (t.getCause() != null) {
t = t.getCause();
}
return t;
}
@Test
void autoConfiguration() {
try (Transcript t = Transcript.open("07-autoconfiguration.txt")) {
t.line("== spring.mail.host, port, username, default-encoding, ssl.enabled and two mail.* properties");
runner.withPropertyValues("spring.mail.host=smtp.example.test", "spring.mail.port=2525",
"spring.mail.username=alice", "spring.mail.ssl.enabled=true",
"spring.mail.properties.mail.smtp.timeout=7000", "spring.mail.properties.mail.smtp.auth=true")
.run(ctx -> {
assertThat(ctx).hasSingleBean(JavaMailSender.class);
JavaMailSenderImpl s = (JavaMailSenderImpl) ctx.getBean(JavaMailSender.class);
t.line("bean : %s", s.getClass().getSimpleName());
t.line("host / port : %s / %s", s.getHost(), s.getPort());
t.line("protocol : %s", s.getProtocol());
t.line("defaultEncoding : %s", s.getDefaultEncoding());
t.line("session props : %s", new TreeMap<>((Map<?, ?>) s.getJavaMailProperties()));
});
t.line("");
t.line("== no spring.mail.host");
runner.run(ctx -> {
t.line("JavaMailSender bean present: %s", ctx.getBeanNamesForType(JavaMailSender.class).length > 0);
assertThat(ctx).doesNotHaveBean(JavaMailSender.class);
});
t.line("");
t.line("== no spring.mail.host, and a bean that needs a JavaMailSender");
runner.withUserConfiguration(NeedsSender.class).run(ctx -> {
assertThat(ctx).hasFailed();
t.line("%s", root(ctx.getStartupFailure()).getMessage().lines().findFirst().orElse(""));
});
t.line("");
t.line("== spring.mail.test-connection=true against a port nothing listens on");
runner.withPropertyValues("spring.mail.host=127.0.0.1", "spring.mail.port=1",
"spring.mail.test-connection=true").run(ctx -> {
assertThat(ctx).hasFailed();
Throwable e = ctx.getStartupFailure();
for (Throwable c = e; c != null; c = c.getCause()) {
t.line("%s: %s", c.getClass().getName(), String.valueOf(c.getMessage()).lines().findFirst().orElse(""));
}
});
}
}
}
@@ -0,0 +1,49 @@
package com.ankurm.email;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/** Accepts TCP connections and never writes a byte: an SMTP server that is up but never sends its greeting. */
final class BlackHole implements AutoCloseable {
private final ServerSocket server;
private final List<Socket> accepted = new CopyOnWriteArrayList<>();
BlackHole() throws IOException {
this.server = new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
Thread.ofVirtual().start(() -> {
while (!server.isClosed()) {
try {
accepted.add(server.accept());
} catch (IOException e) {
return;
}
}
});
}
int port() {
return server.getLocalPort();
}
/** Drops every accepted connection, which unblocks a client stuck reading the greeting. */
void dropAll() {
for (Socket s : accepted) {
try {
s.close();
} catch (IOException ignored) {
// already closed
}
}
}
@Override
public void close() throws IOException {
dropAll();
server.close();
}
}
@@ -0,0 +1,78 @@
package com.ankurm.email;
import static org.assertj.core.api.Assertions.assertThat;
import com.icegreen.greenmail.junit5.GreenMailExtension;
import com.icegreen.greenmail.util.ServerSetupTest;
import jakarta.mail.internet.MimeMessage;
import java.util.Properties;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
/** Non-ASCII subjects, names and bodies on the wire, and what a wrong default encoding does. output/03-encoding.txt. */
@SpringBootTest
class EncodingTest {
@RegisterExtension
static GreenMailExtension greenMail = new GreenMailExtension(ServerSetupTest.SMTP.dynamicPort()).withPerMethodLifecycle(false);
@DynamicPropertySource
static void mail(DynamicPropertyRegistry registry) {
registry.add("spring.mail.port", () -> greenMail.getSmtp().getPort());
registry.add("spring.mail.properties.mail.smtp.auth", () -> "false");
registry.add("spring.mail.properties.mail.smtp.starttls.enable", () -> "false");
registry.add("spring.mail.properties.mail.smtp.starttls.required", () -> "false");
}
@Autowired MailService mail;
@BeforeEach
void clean() throws Exception {
greenMail.purgeEmailFromAllMailboxes();
}
@Test
void encoding() throws Exception {
String subject = "स्वागत है, आशा";
String body = "आपका खाता तैयार है।";
try (Transcript t = Transcript.open("03-encoding.txt")) {
t.line("== default encoding (spring.mail.default-encoding = UTF-8)");
mail.sendInternational("[email protected]", "आशा देशमुख", subject, body);
MimeMessage m = greenMail.getReceivedMessages()[0];
t.line("raw Subject : %s", m.getHeader("Subject", null));
t.line("raw To : %s", m.getHeader("To", null));
t.line("decoded : %s | To name: %s", m.getSubject(), ((jakarta.mail.internet.InternetAddress) m.getAllRecipients()[0]).getPersonal());
t.line("body CTE : %s", m.getHeader("Content-Transfer-Encoding", null));
t.line("body : %s", ((String) m.getContent()).strip());
assertThat(m.getSubject()).isEqualTo(subject);
assertThat(((String) m.getContent()).strip()).isEqualTo(body);
greenMail.purgeEmailFromAllMailboxes();
t.line("");
t.line("== a JavaMailSenderImpl whose defaultEncoding is ISO-8859-1");
JavaMailSenderImpl latin = new JavaMailSenderImpl();
latin.setHost("127.0.0.1");
latin.setPort(greenMail.getSmtp().getPort());
latin.setDefaultEncoding("ISO-8859-1");
latin.setJavaMailProperties(new Properties());
SimpleMailMessage simple = new SimpleMailMessage();
simple.setFrom("[email protected]");
simple.setTo("[email protected]");
simple.setSubject(subject);
simple.setText(body);
latin.send(simple);
MimeMessage l = greenMail.getReceivedMessages()[0];
t.line("raw Subject : %s", l.getHeader("Subject", null));
t.line("decoded : %s", l.getSubject());
t.line("body : %s", ((String) l.getContent()).strip());
assertThat(l.getSubject()).isNotEqualTo(subject);
}
}
}
@@ -0,0 +1,139 @@
package com.ankurm.email;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.icegreen.greenmail.junit5.GreenMailExtension;
import com.icegreen.greenmail.util.ServerSetupTest;
import java.io.IOException;
import java.net.ServerSocket;
import java.time.Duration;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
/** The ways sending fails, and the one way it does not: an infinite wait. Writes output/06-failure-modes.txt. */
class FailureModesTest {
@RegisterExtension
static GreenMailExtension greenMail = new GreenMailExtension(ServerSetupTest.SMTP.dynamicPort()).withPerMethodLifecycle(false);
@BeforeAll
static void user() {
greenMail.setUser("[email protected]", "alice", "s3cret");
}
private static JavaMailSenderImpl sender(int port, String password, Properties extra) {
JavaMailSenderImpl s = new JavaMailSenderImpl();
s.setHost("127.0.0.1");
s.setPort(port);
s.setUsername("alice");
s.setPassword(password);
Properties p = new Properties();
p.put("mail.smtp.auth", "true");
p.putAll(extra);
s.setJavaMailProperties(p);
return s;
}
private static SimpleMailMessage message(String to) {
SimpleMailMessage m = new SimpleMailMessage();
m.setFrom("[email protected]");
m.setTo(to);
m.setSubject("hi");
m.setText("hi");
return m;
}
private static void chain(Transcript t, Throwable e) {
for (Throwable c = e; c != null; c = c.getCause()) {
t.line(" %s: %s", c.getClass().getName(), String.valueOf(c.getMessage()).lines().findFirst().orElse(""));
}
}
@Test
void failures() throws Exception {
try (Transcript t = Transcript.open("06-failure-modes.txt")) {
t.line("== wrong password");
JavaMailSenderImpl wrong = sender(greenMail.getSmtp().getPort(), "nope", new Properties());
assertThatThrownBy(() -> wrong.send(message("[email protected]"))).isInstanceOf(MailAuthenticationException.class);
try {
wrong.send(message("[email protected]"));
} catch (MailException e) {
chain(t, e);
}
t.line("");
t.line("== right password");
sender(greenMail.getSmtp().getPort(), "s3cret", new Properties()).send(message("[email protected]"));
t.line("delivered: %d message", greenMail.getReceivedMessages().length);
assertThat(greenMail.getReceivedMessages()).hasSize(1);
t.line("");
t.line("== nothing listening on the port");
int closed;
try (ServerSocket s = new ServerSocket(0)) {
closed = s.getLocalPort();
}
JavaMailSenderImpl refused = sender(closed, "s3cret", new Properties());
try {
refused.send(message("[email protected]"));
} catch (MailException e) {
t.line("%s", e.getClass().getName());
chain(t, e);
}
t.line("");
t.line("== recipient that is not an address: 'not an address'");
JavaMailSenderImpl ok = sender(greenMail.getSmtp().getPort(), "s3cret", new Properties());
try {
ok.send(message("not an address"));
} catch (MailException e) {
t.line("%s", e.getClass().getName());
chain(t, e);
}
t.line("");
t.line("== server accepts the TCP connection and never sends the SMTP greeting");
for (String[] props : new String[][] {{}, {"mail.smtp.connectiontimeout", "500"}, {"mail.smtp.timeout", "500"}}) {
Properties extra = new Properties();
String label = props.length == 0 ? "no timeouts set" : props[0] + "=" + props[1];
if (props.length > 0) {
extra.put(props[0], props[1]);
}
try (BlackHole hole = new BlackHole()) {
JavaMailSenderImpl s = sender(hole.port(), "s3cret", extra);
long start = System.nanoTime();
CompletableFuture<Void> call = CompletableFuture.runAsync(() -> s.send(message("[email protected]")));
try {
call.get(3, TimeUnit.SECONDS);
} catch (TimeoutException blocked) {
t.line("%-32s -> still blocked after 3000 ms; the caller is stuck", label);
hole.dropAll();
assertThat(props).as("only the read timeout should fail fast").doesNotContain("mail.smtp.timeout");
try {
call.get(5, TimeUnit.SECONDS);
} catch (ExecutionException e) {
t.line("%-32s (after the connection was dropped: %s)", "", e.getCause().getClass().getSimpleName());
}
continue;
} catch (ExecutionException failed) {
long ms = Duration.ofNanos(System.nanoTime() - start).toMillis();
t.line("%-32s -> failed after ~%d ms", label, (ms / 100) * 100);
chain(t, failed.getCause());
assertThat(props).contains("mail.smtp.timeout");
}
}
}
}
}
}
@@ -0,0 +1,94 @@
package com.ankurm.email;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.icegreen.greenmail.junit5.GreenMailExtension;
import com.icegreen.greenmail.util.ServerSetupTest;
import jakarta.mail.internet.MimeMessage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
/** What each way of building a message puts on the wire. Writes output/01-mime-structure.txt. */
@SpringBootTest
class MimeStructureTest {
@RegisterExtension
static GreenMailExtension greenMail = new GreenMailExtension(ServerSetupTest.SMTP.dynamicPort()).withPerMethodLifecycle(false);
@DynamicPropertySource
static void mail(DynamicPropertyRegistry registry) {
registry.add("spring.mail.port", () -> greenMail.getSmtp().getPort());
registry.add("spring.mail.properties.mail.smtp.auth", () -> "false");
registry.add("spring.mail.properties.mail.smtp.starttls.enable", () -> "false");
registry.add("spring.mail.properties.mail.smtp.starttls.required", () -> "false");
}
@Autowired MailService mail;
@Autowired JavaMailSender sender;
@BeforeEach
void clean() throws Exception {
greenMail.purgeEmailFromAllMailboxes();
}
private MimeMessage last() {
MimeMessage[] all = greenMail.getReceivedMessages();
return all[all.length - 1];
}
@Test
void structures() throws Exception {
try (Transcript t = Transcript.open("01-mime-structure.txt")) {
t.line("== 1. SimpleMailMessage (sendPlain)");
mail.sendPlain("[email protected]", "plain", "hello");
MimeTree.print(last(), t);
t.line("");
t.line("== 2. HTML only, non-multipart helper (sendHtmlOnly)");
mail.sendHtmlOnly("[email protected]", "html", "<p>hello</p>");
MimeTree.print(last(), t);
t.line("");
t.line("== 3. welcome: text + HTML + inline logo + PDF attachment");
mail.sendWelcome("[email protected]", "Asha");
MimeTree.print(last(), t);
assertThat(last().getContent()).isInstanceOf(jakarta.mail.Multipart.class);
t.line("");
t.line("== 4. welcome without inline image and without attachment (helper still in multipart mode)");
sender.send(mail.buildWelcome("[email protected]", "Asha", false, false));
MimeTree.print(last(), t);
t.line("");
t.line("== 5. addInline BEFORE setText");
MimeMessage wrong = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(wrong, true);
helper.setTo("[email protected]");
helper.addInline("logo", new ClassPathResource("static/logo.png"));
helper.setText("<img src='cid:logo'>", true);
sender.send(wrong);
MimeTree.print(last(), t);
t.line("");
t.line("== 6. addAttachment on a helper built with multipart=false");
MimeMessage single = sender.createMimeMessage();
MimeMessageHelper flat = new MimeMessageHelper(single, false);
assertThatThrownBy(() -> flat.addAttachment("x.pdf", new ClassPathResource("static/logo.png")))
.isInstanceOf(IllegalStateException.class);
try {
flat.addAttachment("x.pdf", new ClassPathResource("static/logo.png"));
} catch (IllegalStateException e) {
t.line("%s: %s", e.getClass().getSimpleName(), e.getMessage());
}
}
}
}
@@ -0,0 +1,39 @@
package com.ankurm.email;
import jakarta.mail.Multipart;
import jakarta.mail.Part;
/** Prints a message's MIME structure, one part per line, so a transcript shows what actually went on the wire. */
final class MimeTree {
private MimeTree() {
}
static void print(Part part, Transcript t) throws Exception {
walk(part, "", t);
}
private static void walk(Part part, String indent, Transcript t) throws Exception {
String type = part.getContentType()
.replaceAll("(?s);\\s*boundary=\"?[^\";]+\"?", "")
.replaceAll("(?s)\\s+", " ").trim();
StringBuilder line = new StringBuilder(indent).append(type);
if (part.getDisposition() != null) {
line.append(" [").append(part.getDisposition());
if (part.getFileName() != null) {
line.append("; filename=").append(part.getFileName());
}
line.append(']');
}
String[] cid = part.getHeader("Content-ID");
if (cid != null) {
line.append(" [Content-ID ").append(cid[0]).append(']');
}
t.line("%s", line);
if (part.getContent() instanceof Multipart multipart) {
for (int i = 0; i < multipart.getCount(); i++) {
walk(multipart.getBodyPart(i), indent + " ", t);
}
}
}
}
@@ -0,0 +1,81 @@
package com.ankurm.email;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A TCP proxy in front of GreenMail that delays every chunk the server sends back by a fixed time (a stand-in for
* the round trip to a real SMTP provider) and counts the connections it accepted.
*/
final class SlowProxy implements AutoCloseable {
private final ServerSocket server;
private final int targetPort;
private final long delayMillis;
final AtomicInteger connections = new AtomicInteger();
/** Everything clients sent, as text, so a test can show what went over the wire. */
final StringBuffer clientToServer = new StringBuffer();
SlowProxy(int targetPort, long delayMillis) throws IOException {
this.server = new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
this.targetPort = targetPort;
this.delayMillis = delayMillis;
Thread.ofVirtual().start(this::acceptLoop);
}
int port() {
return server.getLocalPort();
}
private void acceptLoop() {
while (!server.isClosed()) {
try {
Socket client = server.accept();
connections.incrementAndGet();
Socket upstream = new Socket(InetAddress.getLoopbackAddress(), targetPort);
pipe(client, upstream, 0, clientToServer);
pipe(upstream, client, delayMillis, null);
} catch (IOException e) {
return;
}
}
}
private void pipe(Socket from, Socket to, long delay, StringBuffer capture) {
Thread.ofVirtual().start(() -> {
byte[] buffer = new byte[8192];
try (InputStream in = from.getInputStream(); OutputStream out = to.getOutputStream()) {
int n;
while ((n = in.read(buffer)) > 0) {
if (delay > 0) {
Thread.sleep(delay);
}
if (capture != null) {
capture.append(new String(buffer, 0, n, java.nio.charset.StandardCharsets.ISO_8859_1));
}
out.write(buffer, 0, n);
out.flush();
}
} catch (IOException | InterruptedException ignored) {
// the other side closed
} finally {
try {
from.close();
to.close();
} catch (IOException ignored) {
// closing anyway
}
}
});
}
@Override
public void close() throws IOException {
server.close();
}
}
@@ -0,0 +1,85 @@
package com.ankurm.email;
import static org.assertj.core.api.Assertions.assertThat;
import com.icegreen.greenmail.junit5.GreenMailExtension;
import com.icegreen.greenmail.util.ServerSetupTest;
import java.util.Base64;
import java.util.Properties;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
/**
* mail.smtp.starttls.enable versus mail.smtp.starttls.required, against an SMTP server that does not offer STARTTLS.
* Writes output/09-starttls.txt.
*/
class StartTlsTest {
@RegisterExtension
static GreenMailExtension greenMail = new GreenMailExtension(ServerSetupTest.SMTP.dynamicPort()).withPerMethodLifecycle(false);
@BeforeAll
static void user() {
greenMail.setUser("[email protected]", "alice", "s3cret");
}
private static JavaMailSenderImpl sender(int port, String tlsProperty) {
JavaMailSenderImpl s = new JavaMailSenderImpl();
s.setHost("127.0.0.1");
s.setPort(port);
s.setUsername("alice");
s.setPassword("s3cret");
Properties p = new Properties();
p.put("mail.smtp.auth", "true");
p.put(tlsProperty, "true");
s.setJavaMailProperties(p);
return s;
}
private static SimpleMailMessage message() {
SimpleMailMessage m = new SimpleMailMessage();
m.setFrom("[email protected]");
m.setTo("[email protected]");
m.setSubject("hi");
m.setText("hi");
return m;
}
@Test
void enableIsNotRequire() throws Exception {
try (Transcript t = Transcript.open("09-starttls.txt"); SlowProxy proxy = new SlowProxy(greenMail.getSmtp().getPort(), 0)) {
t.line("== mail.smtp.starttls.enable=true, server does not advertise STARTTLS");
sender(proxy.port(), "mail.smtp.starttls.enable").send(message());
t.line("delivered: %d message, no error", greenMail.getReceivedMessages().length);
assertThat(greenMail.getReceivedMessages()).hasSize(1);
java.util.List<String> sent = proxy.clientToServer.toString().lines().toList();
int auth = sent.indexOf("AUTH LOGIN");
assertThat(auth).as("AUTH LOGIN line").isGreaterThanOrEqualTo(0);
t.line("client sent: %s", sent.get(auth));
String user = new String(Base64.getDecoder().decode(sent.get(auth + 1)));
String password = new String(Base64.getDecoder().decode(sent.get(auth + 2)));
t.line("client sent: %s (base64 of the user name: %s)", sent.get(auth + 1), user);
t.line("client sent: %s (base64 of the password: %s)", sent.get(auth + 2), password);
assertThat(user).isEqualTo("alice");
assertThat(password).isEqualTo("s3cret");
t.line("");
t.line("== mail.smtp.starttls.required=true, same server");
proxy.clientToServer.setLength(0);
try {
sender(proxy.port(), "mail.smtp.starttls.required").send(message());
} catch (MailException e) {
for (Throwable c = e; c != null; c = c.getCause()) {
t.line(" %s: %s", c.getClass().getName(), String.valueOf(c.getMessage()).lines().findFirst().orElse(""));
}
}
t.line("AUTH line sent: %s", proxy.clientToServer.toString().lines().anyMatch(l -> l.startsWith("AUTH")));
assertThat(greenMail.getReceivedMessages()).hasSize(1);
assertThat(proxy.clientToServer.toString()).doesNotContain("AUTH");
}
}
}
@@ -0,0 +1,82 @@
package com.ankurm.email;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.spring6.SpringTemplateEngine;
/** What Thymeleaf does with the values you pass in. Writes output/02-templates.txt. */
@SpringBootTest
class TemplateTest {
record User(String name) {
}
@Autowired MailService mail;
@Autowired TemplateEngine engine;
@Test
void templates() {
try (Transcript t = Transcript.open("02-templates.txt")) {
t.line("== template resolvers on the engine (class, order, resolvable patterns)");
((SpringTemplateEngine) engine).getTemplateResolvers().forEach(r -> t.line("%s order=%s patterns=%s",
r.getClass().getSimpleName(), r.getOrder(),
r instanceof org.thymeleaf.templateresolver.AbstractConfigurableTemplateResolver c
? c.getResolvablePatterns() : "n/a"));
t.line("");
t.line("== welcome.html with name = Asha");
String html = mail.render("mail/welcome.html", Map.of("name", "Asha"));
t.line("%s", html.lines().filter(l -> l.contains("<h1>")).findFirst().orElseThrow().strip());
assertThat(html).contains("<span>Asha</span>");
t.line("");
t.line("== welcome.txt with name = Asha (TEXT mode)");
String text = mail.render("mail/welcome.txt", Map.of("name", "Asha"));
t.line("%s", text.lines().findFirst().orElseThrow());
assertThat(text).startsWith("Welcome, Asha");
String hostile = "<b>Evil</b> & Co";
t.line("");
t.line("== name = %s", hostile);
String escaped = mail.render("mail/welcome.html", Map.of("name", hostile));
t.line("th:text -> %s", escaped.lines().filter(l -> l.contains("<h1>")).findFirst().orElseThrow().strip());
assertThat(escaped).contains("&lt;b&gt;Evil&lt;/b&gt; &amp; Co");
String raw = mail.render("mail/utext.html", Map.of("name", hostile));
t.line("th:utext -> %s", raw.strip());
assertThat(raw).contains("<b>Evil</b> & Co");
String plain = mail.render("mail/welcome.txt", Map.of("name", hostile));
t.line("[(...)] in TEXT mode -> %s", plain.lines().findFirst().orElseThrow());
assertThat(plain).startsWith("Welcome, <b>Evil</b> & Co");
String textEscaped = mail.render("mail/escaped.txt", Map.of("name", hostile));
t.line("[[...]] in TEXT mode -> %s", textEscaped.strip());
assertThat(textEscaped).contains("&lt;b&gt;Evil&lt;/b&gt; &amp; Co");
t.line("");
t.line("== a typo in a top-level variable name: ${nme} instead of ${name}");
String silent = mail.render("mail/typo.html", Map.of("name", "Asha"));
t.line("%s", silent.strip());
assertThat(silent).contains("<span></span>");
t.line("");
t.line("== a typo in a property of an object you did pass: ${user.nmae}");
assertThatThrownBy(() -> mail.render("mail/typo-property.html", Map.of("user", new User("Asha"))))
.isInstanceOf(org.thymeleaf.exceptions.TemplateProcessingException.class);
try {
mail.render("mail/typo-property.html", Map.of("user", new User("Asha")));
} catch (RuntimeException e) {
Throwable root = e;
while (root.getCause() != null) {
root = root.getCause();
}
t.line("%s", e.getClass().getSimpleName());
t.line("root cause: %s", root.getMessage());
}
}
}
}
@@ -0,0 +1,78 @@
package com.ankurm.email;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.icegreen.greenmail.junit5.GreenMailExtension;
import com.icegreen.greenmail.util.ServerSetupTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.support.AbstractPlatformTransactionManager;
import org.springframework.transaction.support.DefaultTransactionStatus;
/** An email sent inside a transaction that then rolls back. Writes output/08-transactions.txt. */
@SpringBootTest
class TransactionTest {
@RegisterExtension
static GreenMailExtension greenMail = new GreenMailExtension(ServerSetupTest.SMTP.dynamicPort()).withPerMethodLifecycle(false);
@DynamicPropertySource
static void mail(DynamicPropertyRegistry registry) {
registry.add("spring.mail.port", () -> greenMail.getSmtp().getPort());
registry.add("spring.mail.properties.mail.smtp.auth", () -> "false");
registry.add("spring.mail.properties.mail.smtp.starttls.enable", () -> "false");
registry.add("spring.mail.properties.mail.smtp.starttls.required", () -> "false");
}
/** A transaction manager with no resource behind it: enough for @Transactional and AFTER_COMMIT to behave. */
@TestConfiguration
@EnableTransactionManagement
static class Tx {
@Bean
AbstractPlatformTransactionManager transactionManager() {
return new AbstractPlatformTransactionManager() {
@Override protected Object doGetTransaction() { return new Object(); }
@Override protected void doBegin(Object transaction, TransactionDefinition definition) { }
@Override protected void doCommit(DefaultTransactionStatus status) { }
@Override protected void doRollback(DefaultTransactionStatus status) { }
};
}
}
@Autowired OrderService orders;
@BeforeEach
void clean() throws Exception {
greenMail.purgeEmailFromAllMailboxes();
}
@Test
void emailAndRollback() throws Exception {
try (Transcript t = Transcript.open("08-transactions.txt")) {
assertThatThrownBy(() -> orders.placeOrderMailInside("[email protected]", true))
.hasMessage("payment declined");
t.line("send inside the transaction, then roll back : %d email delivered", greenMail.getReceivedMessages().length);
assertThat(greenMail.getReceivedMessages()).hasSize(1);
greenMail.purgeEmailFromAllMailboxes();
assertThatThrownBy(() -> orders.placeOrderMailAfterCommit("[email protected]", true))
.hasMessage("payment declined");
t.line("AFTER_COMMIT listener, then roll back : %d emails delivered", greenMail.getReceivedMessages().length);
assertThat(greenMail.getReceivedMessages()).isEmpty();
orders.placeOrderMailAfterCommit("[email protected]", false);
t.line("AFTER_COMMIT listener, commit : %d email delivered", greenMail.getReceivedMessages().length);
assertThat(greenMail.getReceivedMessages()).hasSize(1);
}
}
}
@@ -0,0 +1,42 @@
package com.ankurm.email;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/**
* Collects the lines a test prints and writes them to {@code output/NN-name.txt}. The same test
* asserts the same numbers, so a line in a transcript is something the build checks.
*/
public final class Transcript implements AutoCloseable {
private final Path file;
private final List<String> lines = new ArrayList<>();
private Transcript(Path file) {
this.file = file;
}
public static Transcript open(String name) {
return new Transcript(Path.of("output", name));
}
public synchronized Transcript line(String format, Object... args) {
String text = args.length == 0 ? format : String.format(format, args);
lines.add(text);
System.out.println(text);
return this;
}
@Override
public synchronized void close() {
try {
Files.createDirectories(file.getParent());
Files.write(file, lines);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
@@ -0,0 +1 @@
Hello, [[${name}]]
@@ -0,0 +1 @@
<p>Hello, <span th:text="${user.nmae}">default</span>!</p>
@@ -0,0 +1 @@
<p>Hello, <span th:text="${nme}">default</span>!</p>
@@ -0,0 +1 @@
<p th:utext="${name}">x</p>