Email Services
Orders confirmation, shipping updates, and password resets should not block the HTTP thread or depend on a homemade SMTP server.
Introduction
Orders confirmation, shipping updates, and password resets should not block the HTTP thread or depend on a homemade SMTP server.
Boot 3 integrates JavaMailSender via spring-boot-starter-mail. Use a transactional provider (SES, SendGrid, Postmark, Resend) with SMTP or their HTTP SDK. Render HTML with Thymeleaf templates.
Send asynchronously with @Async or, better for reliability, publish an outbox event that a worker delivers.
This lesson wires TechLearningPRO Orders welcome/confirmation mail with placeholders for credentials — never real secrets in source.
Purpose of this lesson
Send transactional Orders email with JavaMailSender, templates, and non-blocking delivery on Boot 3.
Understanding the topic
Mail is a side effect: template, send, and isolate failures from checkout.
- JavaMailSender: Boot auto-config from
spring.mail.*. - MimeMessageHelper: HTML + optional attachments.
- templates: Thymeleaf context variables for order id and totals.
- async/outbox: keep place-order latency independent of SMTP.
- provider: managed SMTP — do not run your own MTA in prod.
Step-by-step explanation
- Add
spring-boot-starter-mailand configure host/port via env placeholders. - Create
OrderEmailServicethat builds MimeMessage from a Thymeleaf template. - Call it from an
@Asyncmethod or after-commit outbox handler. - Use
@Profile("!prod")logging sender for local demos.
Informative example
Orders confirmation email service.
@Servicepublic class OrderEmailService {private final JavaMailSender mailer;private final SpringTemplateEngine templates;private final OrdersProps props;public OrderEmailService(JavaMailSender mailer, SpringTemplateEngine templates, OrdersProps props) {this.mailer = mailer;this.templates = templates;this.props = props;}@Asyncpublic void sendOrderPlaced(String to, long orderId, String total) {var ctx = new Context();ctx.setVariable("orderId", orderId);ctx.setVariable("total", total);String html = templates.process("email/order-placed", ctx);try {MimeMessage msg = mailer.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");helper.setFrom(props.mailFrom());helper.setTo(to);helper.setSubject("Order #" + orderId + " confirmed");helper.setText(html, true);mailer.send(msg);} catch (MessagingException e) {throw new MailSendException("Failed to send order mail", e);}}}# application.ymlspring:mail:host: ${SMTP_HOST}port: ${SMTP_PORT:587}username: ${SMTP_USER}password: ${SMTP_PASSWORD}properties:mail.smtp.starttls.enable: true
Real-world use
Checkout once waited synchronously on SMTP and timed out during a provider blip, rolling back orders that had already reserved stock. Moving mail to after-commit async delivery kept the purchase successful and retried email separately.
Security implications
Email paths can leak accounts and enable phishing if abused.
- Do not include raw reset tokens in logs.
- Rate-limit password-reset and confirmation endpoints.
- SMTP credentials only via
${SMTP_USER}/${SMTP_PASSWORD}.
Best practices
- Template engines escape by default — keep it that way.
- Prefer outbox + worker for durable delivery; @Async for best-effort only.
- Track bounce/complaint webhooks from the provider when volume grows.
Common mistakes
- Sending email inside the same transaction as order insert without after-commit semantics.
- Hard-coding from-addresses or SMTP passwords in YAML.
- Building HTML with string concatenation that allows injection from user fields.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhy send order email asynchronously?+
Answer
2IntermediateQuestionJavaMailSender vs provider HTTP APIs?+
Answer
3AdvancedQuestionWhat is the outbox pattern for email?+
Answer
Hands-on exercise
Lab. Implement OrderEmailService.sendOrderPlaced with a Thymeleaf template. Trigger it via @Async after a successful place-order. Under the dev profile, swap in a logging sender.
Summary
Email services for TechLearningPRO Orders deliver confirmations through JavaMailSender and templates while keeping SMTP failures off the critical checkout path.