From da700a564f8c852702d7074e85ac95111ce4f5ed Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 21:15:21 +0530 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_017ic4b7SK2mvUEELeLtMi1o --- README.md | 1 + email/README.md | 50 ++++++ email/output/01-mime-structure.txt | 30 ++++ email/output/02-templates.txt | 22 +++ email/output/03-encoding.txt | 11 ++ email/output/04-async-and-connections.txt | 5 + email/output/05-async-failures.txt | 8 + email/output/06-failure-modes.txt | 27 +++ email/output/07-autoconfiguration.txt | 19 +++ email/output/08-transactions.txt | 3 + email/output/09-starttls.txt | 10 ++ email/output/10-no-mail-host.txt | 12 ++ email/output/11-test-summary.txt | 9 + email/pom.xml | 71 ++++++++ email/scripts/no-mail-host.sh | 10 ++ email/scripts/run-all.sh | 21 +++ .../com/ankurm/email/AsyncMailService.java | 41 +++++ .../com/ankurm/email/EmailApplication.java | 19 +++ .../java/com/ankurm/email/MailService.java | 119 +++++++++++++ .../com/ankurm/email/MailTemplateConfig.java | 27 +++ .../com/ankurm/email/OrderMailListener.java | 21 +++ .../java/com/ankurm/email/OrderPlaced.java | 5 + .../java/com/ankurm/email/OrderService.java | 39 +++++ .../src/main/java/com/ankurm/email/Pdfs.java | 22 +++ email/src/main/resources/application.yml | 20 +++ email/src/main/resources/static/logo.png | Bin 0 -> 73 bytes .../resources/templates/mail/welcome.html | 8 + .../main/resources/templates/mail/welcome.txt | 3 + .../ankurm/email/AsyncAndConnectionsTest.java | 158 ++++++++++++++++++ .../ankurm/email/AutoConfigurationTest.java | 76 +++++++++ .../test/java/com/ankurm/email/BlackHole.java | 49 ++++++ .../java/com/ankurm/email/EncodingTest.java | 78 +++++++++ .../com/ankurm/email/FailureModesTest.java | 139 +++++++++++++++ .../com/ankurm/email/MimeStructureTest.java | 94 +++++++++++ .../test/java/com/ankurm/email/MimeTree.java | 39 +++++ .../test/java/com/ankurm/email/SlowProxy.java | 81 +++++++++ .../java/com/ankurm/email/StartTlsTest.java | 85 ++++++++++ .../java/com/ankurm/email/TemplateTest.java | 82 +++++++++ .../com/ankurm/email/TransactionTest.java | 78 +++++++++ .../java/com/ankurm/email/Transcript.java | 42 +++++ .../test/resources/templates/mail/escaped.txt | 1 + .../templates/mail/typo-property.html | 1 + .../test/resources/templates/mail/typo.html | 1 + .../test/resources/templates/mail/utext.html | 1 + 44 files changed, 1638 insertions(+) create mode 100644 email/README.md create mode 100644 email/output/01-mime-structure.txt create mode 100644 email/output/02-templates.txt create mode 100644 email/output/03-encoding.txt create mode 100644 email/output/04-async-and-connections.txt create mode 100644 email/output/05-async-failures.txt create mode 100644 email/output/06-failure-modes.txt create mode 100644 email/output/07-autoconfiguration.txt create mode 100644 email/output/08-transactions.txt create mode 100644 email/output/09-starttls.txt create mode 100644 email/output/10-no-mail-host.txt create mode 100644 email/output/11-test-summary.txt create mode 100644 email/pom.xml create mode 100755 email/scripts/no-mail-host.sh create mode 100755 email/scripts/run-all.sh create mode 100644 email/src/main/java/com/ankurm/email/AsyncMailService.java create mode 100644 email/src/main/java/com/ankurm/email/EmailApplication.java create mode 100644 email/src/main/java/com/ankurm/email/MailService.java create mode 100644 email/src/main/java/com/ankurm/email/MailTemplateConfig.java create mode 100644 email/src/main/java/com/ankurm/email/OrderMailListener.java create mode 100644 email/src/main/java/com/ankurm/email/OrderPlaced.java create mode 100644 email/src/main/java/com/ankurm/email/OrderService.java create mode 100644 email/src/main/java/com/ankurm/email/Pdfs.java create mode 100644 email/src/main/resources/application.yml create mode 100644 email/src/main/resources/static/logo.png create mode 100644 email/src/main/resources/templates/mail/welcome.html create mode 100644 email/src/main/resources/templates/mail/welcome.txt create mode 100644 email/src/test/java/com/ankurm/email/AsyncAndConnectionsTest.java create mode 100644 email/src/test/java/com/ankurm/email/AutoConfigurationTest.java create mode 100644 email/src/test/java/com/ankurm/email/BlackHole.java create mode 100644 email/src/test/java/com/ankurm/email/EncodingTest.java create mode 100644 email/src/test/java/com/ankurm/email/FailureModesTest.java create mode 100644 email/src/test/java/com/ankurm/email/MimeStructureTest.java create mode 100644 email/src/test/java/com/ankurm/email/MimeTree.java create mode 100644 email/src/test/java/com/ankurm/email/SlowProxy.java create mode 100644 email/src/test/java/com/ankurm/email/StartTlsTest.java create mode 100644 email/src/test/java/com/ankurm/email/TemplateTest.java create mode 100644 email/src/test/java/com/ankurm/email/TransactionTest.java create mode 100644 email/src/test/java/com/ankurm/email/Transcript.java create mode 100644 email/src/test/resources/templates/mail/escaped.txt create mode 100644 email/src/test/resources/templates/mail/typo-property.html create mode 100644 email/src/test/resources/templates/mail/typo.html create mode 100644 email/src/test/resources/templates/mail/utext.html diff --git a/README.md b/README.md index 1e086b4..32e93be 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ files. | Directory | Article | What it demonstrates | |---|---|---| +| [`email/`](email) | [Sending Emails in Spring Boot 4: SMTP, HTML Templates, Attachments and Testing](https://ankurm.com/sending-emails-in-spring-boot-3-a-complete-guide/) | the MIME tree of six message shapes (`multipart/mixed` > `related` > `alternative`, and `addInline` before `setText` putting the image first), Thymeleaf HTML and TEXT templates (`[[...]]` still HTML-escapes in TEXT mode), Devanagari subjects as encoded-words and a wrong `defaultEncoding` turning them into `?`, one `send` per message (5 connections) vs the varargs `send` (1), `@Async` returning in milliseconds and a `void @Async` failure that never reaches the caller, a server that never greets blocking forever until `mail.smtp.timeout` is set (`connectiontimeout` does not help), `starttls.enable` authenticating in plain text while `starttls.required` refuses, an email still sent when the transaction rolls back unless it waits for `AFTER_COMMIT`, all against GreenMail on Spring Boot 4.1.2 | | [`log4j2-levels/`](log4j2-levels) | [Log4j2 Logging Levels Explained: Configuration, Custom Levels and Changing Levels at Runtime](https://ankurm.com/log4j2-logging-levels-complete-guide/) | the threshold rule printed as a matrix, a level inherited from the nearest configured ancestor, a logger with its own appender and default additivity printing every line twice, custom `DIAG`/`PERF` levels between the standard ones, `/actuator/loggers` rejecting a custom level and a `null` reset landing on the root's level instead of the XML's, `logging.level.*` beating the XML and a custom level in that property stopping the app at startup, argument `toString()` counts for six call shapes, and Logback plus Log4j2 on one classpath silently handing everything to Logback | | [`idempotency/`](idempotency) | [Idempotency Keys for POST APIs in Spring Boot (Stripe-Style) with Redis and Postgres](https://ankurm.com/idempotency-keys-spring-boot-redis-postgres/) | one servlet filter and two interchangeable stores: a retried POST after a client timeout creating two payments without a key and one with; 400 / 422 / 409 and replay with `Idempotent-Replayed`; ten simultaneous duplicates (nine `409` on Redis, nine replays on Postgres because the second `INSERT` waits on the first's uncommitted row); a crash after the payment commits leaving Redis with a stuck lock and then a duplicate payment, and Postgres with neither; a handler slower than the Redis lock finishing with nothing stored; the legacy `Asia/Calcutta` zone id that PostgreSQL 16 refuses at connect time | | [`http-service-clients/`](http-service-clients) | [Spring Boot 4 HTTP Service Clients: @HttpExchange Interfaces with RestClient (Complete Guide)](https://ankurm.com/spring-boot-4-http-service-clients/) | `@HttpExchange` interfaces registered with `@ImportHttpServices` and configured under `spring.http.serviceclient..*` (the keys the first version of the post gave are silently ignored), run against a local stub upstream: `defaultStatusHandler` with ProblemDetail decoding, `NotFoundRestClientAdapterDecorator` for `Optional` on a 404, Framework 7 `@Retryable` on the interface vs `RetryTemplate` vs an interceptor vs Resilience4j (call counts side by side, and a retried POST created twice), bearer, API-key and OAuth2 client-credentials auth (`@ClientRegistrationId` ignored without its group configurer), `MockRestServiceServer`, and the `@RestClientTest` slice where a group client is not bound to the mock | diff --git a/email/README.md b/email/README.md new file mode 100644 index 0000000..d4cef2a --- /dev/null +++ b/email/README.md @@ -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. diff --git a/email/output/01-mime-structure.txt b/email/output/01-mime-structure.txt new file mode 100644 index 0000000..91df2cb --- /dev/null +++ b/email/output/01-mime-structure.txt @@ -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 ] + 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 ] + 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. diff --git a/email/output/02-templates.txt b/email/output/02-templates.txt new file mode 100644 index 0000000..80a9b38 --- /dev/null +++ b/email/output/02-templates.txt @@ -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 +

Welcome, Asha

+ +== welcome.txt with name = Asha (TEXT mode) +Welcome, Asha + +== name = Evil & Co +th:text ->

Welcome, <b>Evil</b> & Co

+th:utext ->

Evil & Co

+[(...)] in TEXT mode -> Welcome, Evil & Co +[[...]] in TEXT mode -> Hello, <b>Evil</b> & Co + +== a typo in a top-level variable name: ${nme} instead of ${name} +

Hello, !

+ +== 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? diff --git a/email/output/03-encoding.txt b/email/output/03-encoding.txt new file mode 100644 index 0000000..732e6aa --- /dev/null +++ b/email/output/03-encoding.txt @@ -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==?= +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 : ???? ???? ????? ??? diff --git a/email/output/04-async-and-connections.txt b/email/output/04-async-and-connections.txt new file mode 100644 index 0000000..15c7aa9 --- /dev/null +++ b/email/output/04-async-and-connections.txt @@ -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] diff --git a/email/output/05-async-failures.txt b/email/output/05-async-failures.txt new file mode 100644 index 0000000..56d8ed2 --- /dev/null +++ b/email/output/05-async-failures.txt @@ -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 @Async, same recipient +future.get() threw ExecutionException +cause: jakarta.mail.internet.AddressException: Local address contains control or whitespace diff --git a/email/output/06-failure-modes.txt b/email/output/06-failure-modes.txt new file mode 100644 index 0000000..6c28335 --- /dev/null +++ b/email/output/06-failure-modes.txt @@ -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 diff --git a/email/output/07-autoconfiguration.txt b/email/output/07-autoconfiguration.txt new file mode 100644 index 0000000..b1c4d10 --- /dev/null +++ b/email/output/07-autoconfiguration.txt @@ -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 diff --git a/email/output/08-transactions.txt b/email/output/08-transactions.txt new file mode 100644 index 0000000..834f3ea --- /dev/null +++ b/email/output/08-transactions.txt @@ -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 diff --git a/email/output/09-starttls.txt b/email/output/09-starttls.txt new file mode 100644 index 0000000..28bc5dd --- /dev/null +++ b/email/output/09-starttls.txt @@ -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 diff --git a/email/output/10-no-mail-host.txt b/email/output/10-no-mail-host.txt new file mode 100644 index 0000000..42e9c04 --- /dev/null +++ b/email/output/10-no-mail-host.txt @@ -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. + diff --git a/email/output/11-test-summary.txt b/email/output/11-test-summary.txt new file mode 100644 index 0000000..8d6bf9f --- /dev/null +++ b/email/output/11-test-summary.txt @@ -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 diff --git a/email/pom.xml b/email/pom.xml new file mode 100644 index 0000000..40ca583 --- /dev/null +++ b/email/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.1.2 + + + + com.ankurm + email + 1.0.0 + email + 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. + jar + + + 25 + 2.1.15 + + + + + org.springframework.boot + spring-boot-starter-mail + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + + org.springframework + spring-tx + + + + org.springframework.boot + spring-boot-starter-test + test + + + com.icegreen + greenmail-junit5 + ${greenmail.version} + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + -Duser.timezone=UTC -Dfile.encoding=UTF-8 + + + + + diff --git a/email/scripts/no-mail-host.sh b/email/scripts/no-mail-host.sh new file mode 100755 index 0000000..d66c084 --- /dev/null +++ b/email/scripts/no-mail-host.sh @@ -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 diff --git a/email/scripts/run-all.sh b/email/scripts/run-all.sh new file mode 100755 index 0000000..2f4b075 --- /dev/null +++ b/email/scripts/run-all.sh @@ -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 diff --git a/email/src/main/java/com/ankurm/email/AsyncMailService.java b/email/src/main/java/com/ankurm/email/AsyncMailService.java new file mode 100644 index 0000000..59acb7a --- /dev/null +++ b/email/src/main/java/com/ankurm/email/AsyncMailService.java @@ -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 sendWelcome(String to, String name) { + try { + mail.sendWelcome(to, name); + return CompletableFuture.completedFuture(Thread.currentThread().getName()); + } catch (MessagingException | RuntimeException e) { + return CompletableFuture.failedFuture(e); + } + } +} diff --git a/email/src/main/java/com/ankurm/email/EmailApplication.java b/email/src/main/java/com/ankurm/email/EmailApplication.java new file mode 100644 index 0000000..1d7b50f --- /dev/null +++ b/email/src/main/java/com/ankurm/email/EmailApplication.java @@ -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); + } +} diff --git a/email/src/main/java/com/ankurm/email/MailService.java b/email/src/main/java/com/ankurm/email/MailService.java new file mode 100644 index 0000000..c2bbb78 --- /dev/null +++ b/email/src/main/java/com/ankurm/email/MailService.java @@ -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:noreply@example.test}") 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 variables) { + Context context = new Context(); + variables.forEach(context::setVariable); + return templates.process(template, context); + } +} diff --git a/email/src/main/java/com/ankurm/email/MailTemplateConfig.java b/email/src/main/java/com/ankurm/email/MailTemplateConfig.java new file mode 100644 index 0000000..20cf494 --- /dev/null +++ b/email/src/main/java/com/ankurm/email/MailTemplateConfig.java @@ -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; + } +} diff --git a/email/src/main/java/com/ankurm/email/OrderMailListener.java b/email/src/main/java/com/ankurm/email/OrderMailListener.java new file mode 100644 index 0000000..7d7a1d1 --- /dev/null +++ b/email/src/main/java/com/ankurm/email/OrderMailListener.java @@ -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."); + } +} diff --git a/email/src/main/java/com/ankurm/email/OrderPlaced.java b/email/src/main/java/com/ankurm/email/OrderPlaced.java new file mode 100644 index 0000000..cf3f189 --- /dev/null +++ b/email/src/main/java/com/ankurm/email/OrderPlaced.java @@ -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) { +} diff --git a/email/src/main/java/com/ankurm/email/OrderService.java b/email/src/main/java/com/ankurm/email/OrderService.java new file mode 100644 index 0000000..e881dd8 --- /dev/null +++ b/email/src/main/java/com/ankurm/email/OrderService.java @@ -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"); + } + } +} diff --git a/email/src/main/java/com/ankurm/email/Pdfs.java b/email/src/main/java/com/ankurm/email/Pdfs.java new file mode 100644 index 0000000..f7d91c9 --- /dev/null +++ b/email/src/main/java/com/ankurm/email/Pdfs.java @@ -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); + } +} diff --git a/email/src/main/resources/application.yml b/email/src/main/resources/application.yml new file mode 100644 index 0000000..ff24095 --- /dev/null +++ b/email/src/main/resources/application.yml @@ -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: noreply@example.test diff --git a/email/src/main/resources/static/logo.png b/email/src/main/resources/static/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..e7e9f2bbf9556a6428552b604fe9fe45cb766b5a GIT binary patch literal 73 zcmeAS@N?(olHy`uVBq!ia0vp^EFjFm1SHiab7}%90Z$jlkcv6U7dosM-Fc1_GVo0j VSy{eG5Gw!x literal 0 HcmV?d00001 diff --git a/email/src/main/resources/templates/mail/welcome.html b/email/src/main/resources/templates/mail/welcome.html new file mode 100644 index 0000000..a6fbe34 --- /dev/null +++ b/email/src/main/resources/templates/mail/welcome.html @@ -0,0 +1,8 @@ + + + + logo +

Welcome, Friend

+

Your account is ready. The attached PDF has the short version of how to get started.

+ + diff --git a/email/src/main/resources/templates/mail/welcome.txt b/email/src/main/resources/templates/mail/welcome.txt new file mode 100644 index 0000000..7df79a8 --- /dev/null +++ b/email/src/main/resources/templates/mail/welcome.txt @@ -0,0 +1,3 @@ +Welcome, [(${name})] + +Your account is ready. The attached PDF has the short version of how to get started. diff --git a/email/src/test/java/com/ankurm/email/AsyncAndConnectionsTest.java b/email/src/test/java/com/ankurm/email/AsyncAndConnectionsTest.java new file mode 100644 index 0000000..17af136 --- /dev/null +++ b/email/src/test/java/com/ankurm/email/AsyncAndConnectionsTest.java @@ -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> 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 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 @Async, same recipient"); + CompletableFuture 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()); + } + } + } +} diff --git a/email/src/test/java/com/ankurm/email/AutoConfigurationTest.java b/email/src/test/java/com/ankurm/email/AutoConfigurationTest.java new file mode 100644 index 0000000..e88990b --- /dev/null +++ b/email/src/test/java/com/ankurm/email/AutoConfigurationTest.java @@ -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("")); + } + }); + } + } +} diff --git a/email/src/test/java/com/ankurm/email/BlackHole.java b/email/src/test/java/com/ankurm/email/BlackHole.java new file mode 100644 index 0000000..ca9d454 --- /dev/null +++ b/email/src/test/java/com/ankurm/email/BlackHole.java @@ -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 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(); + } +} diff --git a/email/src/test/java/com/ankurm/email/EncodingTest.java b/email/src/test/java/com/ankurm/email/EncodingTest.java new file mode 100644 index 0000000..852f5a0 --- /dev/null +++ b/email/src/test/java/com/ankurm/email/EncodingTest.java @@ -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("asha@example.test", "आशा देशमुख", 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("noreply@example.test"); + simple.setTo("asha@example.test"); + 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); + } + } +} diff --git a/email/src/test/java/com/ankurm/email/FailureModesTest.java b/email/src/test/java/com/ankurm/email/FailureModesTest.java new file mode 100644 index 0000000..580a2af --- /dev/null +++ b/email/src/test/java/com/ankurm/email/FailureModesTest.java @@ -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("alice@example.test", "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("noreply@example.test"); + 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("a@example.test"))).isInstanceOf(MailAuthenticationException.class); + try { + wrong.send(message("a@example.test")); + } catch (MailException e) { + chain(t, e); + } + + t.line(""); + t.line("== right password"); + sender(greenMail.getSmtp().getPort(), "s3cret", new Properties()).send(message("a@example.test")); + 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("a@example.test")); + } 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 call = CompletableFuture.runAsync(() -> s.send(message("a@example.test"))); + 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"); + } + } + } + } + } +} diff --git a/email/src/test/java/com/ankurm/email/MimeStructureTest.java b/email/src/test/java/com/ankurm/email/MimeStructureTest.java new file mode 100644 index 0000000..4082296 --- /dev/null +++ b/email/src/test/java/com/ankurm/email/MimeStructureTest.java @@ -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("a@example.test", "plain", "hello"); + MimeTree.print(last(), t); + + t.line(""); + t.line("== 2. HTML only, non-multipart helper (sendHtmlOnly)"); + mail.sendHtmlOnly("a@example.test", "html", "

hello

"); + MimeTree.print(last(), t); + + t.line(""); + t.line("== 3. welcome: text + HTML + inline logo + PDF attachment"); + mail.sendWelcome("a@example.test", "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("a@example.test", "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("a@example.test"); + helper.addInline("logo", new ClassPathResource("static/logo.png")); + helper.setText("", 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()); + } + } + } +} diff --git a/email/src/test/java/com/ankurm/email/MimeTree.java b/email/src/test/java/com/ankurm/email/MimeTree.java new file mode 100644 index 0000000..3fc5e15 --- /dev/null +++ b/email/src/test/java/com/ankurm/email/MimeTree.java @@ -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); + } + } + } +} diff --git a/email/src/test/java/com/ankurm/email/SlowProxy.java b/email/src/test/java/com/ankurm/email/SlowProxy.java new file mode 100644 index 0000000..b5cfb2d --- /dev/null +++ b/email/src/test/java/com/ankurm/email/SlowProxy.java @@ -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(); + } +} diff --git a/email/src/test/java/com/ankurm/email/StartTlsTest.java b/email/src/test/java/com/ankurm/email/StartTlsTest.java new file mode 100644 index 0000000..5850147 --- /dev/null +++ b/email/src/test/java/com/ankurm/email/StartTlsTest.java @@ -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("alice@example.test", "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("noreply@example.test"); + m.setTo("a@example.test"); + 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 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"); + } + } +} diff --git a/email/src/test/java/com/ankurm/email/TemplateTest.java b/email/src/test/java/com/ankurm/email/TemplateTest.java new file mode 100644 index 0000000..02c6dc1 --- /dev/null +++ b/email/src/test/java/com/ankurm/email/TemplateTest.java @@ -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("

")).findFirst().orElseThrow().strip()); + assertThat(html).contains("Asha"); + + 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 = "Evil & 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("

")).findFirst().orElseThrow().strip()); + assertThat(escaped).contains("<b>Evil</b> & Co"); + String raw = mail.render("mail/utext.html", Map.of("name", hostile)); + t.line("th:utext -> %s", raw.strip()); + assertThat(raw).contains("Evil & 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, Evil & Co"); + String textEscaped = mail.render("mail/escaped.txt", Map.of("name", hostile)); + t.line("[[...]] in TEXT mode -> %s", textEscaped.strip()); + assertThat(textEscaped).contains("<b>Evil</b> & 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(""); + + 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()); + } + } + } +} diff --git a/email/src/test/java/com/ankurm/email/TransactionTest.java b/email/src/test/java/com/ankurm/email/TransactionTest.java new file mode 100644 index 0000000..9d46661 --- /dev/null +++ b/email/src/test/java/com/ankurm/email/TransactionTest.java @@ -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("a@example.test", 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("a@example.test", true)) + .hasMessage("payment declined"); + t.line("AFTER_COMMIT listener, then roll back : %d emails delivered", greenMail.getReceivedMessages().length); + assertThat(greenMail.getReceivedMessages()).isEmpty(); + + orders.placeOrderMailAfterCommit("a@example.test", false); + t.line("AFTER_COMMIT listener, commit : %d email delivered", greenMail.getReceivedMessages().length); + assertThat(greenMail.getReceivedMessages()).hasSize(1); + } + } +} diff --git a/email/src/test/java/com/ankurm/email/Transcript.java b/email/src/test/java/com/ankurm/email/Transcript.java new file mode 100644 index 0000000..92d2380 --- /dev/null +++ b/email/src/test/java/com/ankurm/email/Transcript.java @@ -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 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); + } + } +} diff --git a/email/src/test/resources/templates/mail/escaped.txt b/email/src/test/resources/templates/mail/escaped.txt new file mode 100644 index 0000000..3019a3a --- /dev/null +++ b/email/src/test/resources/templates/mail/escaped.txt @@ -0,0 +1 @@ +Hello, [[${name}]] diff --git a/email/src/test/resources/templates/mail/typo-property.html b/email/src/test/resources/templates/mail/typo-property.html new file mode 100644 index 0000000..a58178f --- /dev/null +++ b/email/src/test/resources/templates/mail/typo-property.html @@ -0,0 +1 @@ +

Hello, default!

diff --git a/email/src/test/resources/templates/mail/typo.html b/email/src/test/resources/templates/mail/typo.html new file mode 100644 index 0000000..865541f --- /dev/null +++ b/email/src/test/resources/templates/mail/typo.html @@ -0,0 +1 @@ +

Hello, default!

diff --git a/email/src/test/resources/templates/mail/utext.html b/email/src/test/resources/templates/mail/utext.html new file mode 100644 index 0000000..050034c --- /dev/null +++ b/email/src/test/resources/templates/mail/utext.html @@ -0,0 +1 @@ +

x