Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 53

    Email Services

    Orders confirmation, shipping updates, and password resets should not block the HTTP thread or depend on a homemade SMTP server.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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

    1. Add spring-boot-starter-mail and configure host/port via env placeholders.
    2. Create OrderEmailService that builds MimeMessage from a Thymeleaf template.
    3. Call it from an @Async method or after-commit outbox handler.
    4. Use @Profile("!prod") logging sender for local demos.

    Informative example

    Orders confirmation email service.

    java
    @Service
    public 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;
    }
    @Async
    public 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.yml
    spring:
    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.

    3 questions
    1BeginnerQuestionWhy send order email asynchronously?+

    Answer

    SMTP latency and outages should not fail or slow the purchase transaction; async or outbox isolates the side effect.
    2IntermediateQuestionJavaMailSender vs provider HTTP APIs?+

    Answer

    JavaMailSender uses SMTP and is fine for many apps; HTTP SDKs add richer templates/analytics — both should keep credentials external.
    3AdvancedQuestionWhat is the outbox pattern for email?+

    Answer

    Write the order and an outbox row in one DB transaction; a poller sends mail and marks the row processed so crashes do not lose or double-send carelessly.

    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.

    Ready to mark this lesson complete?Track your journey across the entire course.