Skip to content
Tutorials Center
My learning

Topics

Lesson 90 of 119 ยท Spring Boot

Sending Email with Jakarta Mail and Spring Mail

Send email from Java with Jakarta Mail and Spring's JavaMailSender - SMTP and TLS, MimeMessage, HTML, attachments, templates, async sending and test mail servers like Mailpit and GreenMail.

Almost every application sends email: sign-up confirmations, password resets, invoices, alerts, weekly reports. In Java the standard tool is Jakarta Mail (formerly JavaMail, package jakarta.mail, with Eclipse Angus Mail as the implementation). Spring wraps it in JavaMailSender, and Spring Boot configures that sender from a few properties. Under all of it sits a plain-text protocol, SMTP, which is easy to understand once you see it.

In this lesson you will learn how an email travels, what a MIME message looks like on the wire, how to send plain text, HTML and attachments with Jakarta Mail and with Spring, and how to test and operate email sending safely. The mail libraries are not on this course's code runner, so the real API code is read-only. Runnable programs show the layers underneath with the JDK alone: an SMTP conversation over a real loopback socket, and the construction of a multipart MIME message with Base64.

How email travels

You never talk to the recipient's server directly. Your application hands the message to an SMTP server (your provider or company relay, called the submission server). That server looks up the recipient domain's MX records in DNS and relays the message onward, possibly through several hops, until it reaches the recipient's mailbox. Reading mail is a different protocol (IMAP or POP3).

Port Protocol Notes
25 SMTP server-to-server relay; usually blocked for applications
587 SMTP submission + STARTTLS the standard for applications: starts plain, upgrades to TLS, then authenticates
465 SMTP over implicit TLS (SMTPS) TLS from the first byte

An SMTP session is a short dialogue of text commands and three-digit replies. Codes starting with 2 mean success, 4 a temporary failure (retry later), and 5 a permanent failure. This program runs a tiny SMTP server on the loopback address and a client that speaks to it, printing the whole conversation. The same dialogue happens whenever Jakarta Mail sends a message, and it is exactly what test servers like Mailpit and GreenMail record:

Java An SMTP conversation on loopback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The message body is terminated by a line containing only a dot. Because a message line could itself start with a dot, the client doubles it (dot-stuffing) and the server removes the extra dot, which is why the stored message shows the single dot intact.

What a MIME message looks like

Plain SMTP only moves text lines. MIME is the layer that allows non-ASCII text, HTML and attachments. A message is a tree of parts:

  • multipart/mixed holds the body plus attachments.
  • multipart/alternative holds several versions of the same content (plain text and HTML); the mail client shows the best one it supports.
  • multipart/related holds an HTML body together with images it references with cid: URLs (inline images).
  • Leaf parts have a content type (text/html, application/pdf) and a transfer encoding (base64 or quoted-printable) so binary data survives the 7-bit text channel.

Header values with non-ASCII characters use encoded words such as =?UTF-8?B?...?=. Building all this by hand is tedious, which is why you use a library, but the next program does it once with only java.util.Base64 so you can see what the library generates:

Java A multipart MIME message built by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The structure printout is the tree: a mixed container holds an alternative block with two body versions, and then the attachment. Always send both a plain-text and an HTML version; spam filters and accessibility tools notice when text is missing.

Jakarta Mail

With the library you describe the message in objects and let it generate the MIME above. Add the dependencies jakarta.mail:jakarta.mail-api and an implementation such as org.eclipse.angus:angus-mail.

Java
import jakarta.mail.*;
import jakarta.mail.internet.*;
import java.util.Properties;

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");           // upgrade to TLS before logging in
props.put("mail.smtp.starttls.required", "true");         // never send credentials in clear text
props.put("mail.smtp.connectiontimeout", "5000");         // always set timeouts: the default is infinite
props.put("mail.smtp.timeout", "10000");

Session session = Session.getInstance(props, new Authenticator() {
    @Override protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(System.getenv("SMTP_USER"), System.getenv("SMTP_PASSWORD"));
    }
});

MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]", "Example Shop"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
message.setSubject("Your invoice", "UTF-8");

MimeBodyPart text = new MimeBodyPart();
text.setContent("<p>Hi <b>Ana</b>, your invoice is attached.</p>", "text/html; charset=UTF-8");

MimeBodyPart attachment = new MimeBodyPart();
attachment.attachFile(new java.io.File("invoice.pdf"));   // sets Content-Disposition and the file name

Multipart multipart = new MimeMultipart();                 // multipart/mixed
multipart.addBodyPart(text);
multipart.addBodyPart(attachment);
message.setContent(multipart);

Transport.send(message);                                   // opens SMTP, authenticates, sends, closes

Points to remember:

  • A Session holds configuration; build it once and reuse it. Credentials come from the environment or a secrets store, never from source code.
  • Transport.send opens a new connection each time. For bulk sending, open one Transport, call connect, send many messages with sendMessage, then close.
  • Sending blocks and can fail with MessagingException (a transient network error, a rejected recipient). Never send inside a user-facing request thread without handling that.

Spring's JavaMailSender

Add spring-boot-starter-mail and Spring Boot creates a JavaMailSender from properties:

YAML
spring:
  mail:
    host: smtp.example.com
    port: 587
    username: ${SMTP_USER}
    password: ${SMTP_PASSWORD}
    properties:
      mail.smtp.auth: true
      mail.smtp.starttls.enable: true
      mail.smtp.connectiontimeout: 5000
      mail.smtp.timeout: 10000

Inject the sender and use SimpleMailMessage for plain text, or MimeMessageHelper for everything else:

Java
@Service
public class MailService {

    private final JavaMailSender mailSender;

    public MailService(JavaMailSender mailSender) { this.mailSender = mailSender; }

    public void sendWelcome(String to) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("[email protected]");
        message.setTo(to);
        message.setSubject("Welcome!");
        message.setText("Thanks for signing up.");
        mailSender.send(message);
    }

    public void sendInvoice(String to, String html, Path pdf) throws MessagingException {
        MimeMessage mime = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mime, true, "UTF-8");   // true = multipart
        helper.setFrom("[email protected]");
        helper.setTo(to);
        helper.setSubject("Your invoice");
        helper.setText("Your invoice is attached.", html);                       // plain text AND HTML alternative
        helper.addAttachment("invoice.pdf", new FileSystemResource(pdf));
        helper.addInline("logo", new ClassPathResource("static/logo.png"));       // <img src="cid:logo">
        mailSender.send(mime);
    }
}

setText(plain, html) creates the multipart/alternative structure you built by hand above. addInline puts the image into a multipart/related part, referenced from the HTML as cid:logo. Failures surface as unchecked MailException subclasses (MailSendException, MailAuthenticationException), consistent with Spring's exception translation.

Templates and asynchronous sending

Hand-assembled HTML strings do not scale. Render the body from a template with the Thymeleaf engine (templateEngine.process("mail/invoice", context)), which keeps design in a file that designers can edit. Because SMTP is slow and can fail, send mail outside the request: annotate the method with @Async (see scheduling, caching and async), or better, publish an event after the transaction commits (see Spring transactions and events), so no email is sent for an order that was rolled back. For important mail add retries, or put messages on a queue as in JMS.

Testing email

Never test against a real SMTP provider and never send test mail to real people. Use a test mail server that accepts everything and shows it in a web page:

Tool How it helps
Mailpit (or MailHog) a Docker container with SMTP on 1025 and a web inbox on 8025; point spring.mail.host=localhost and port=1025 in development
GreenMail an embedded SMTP/IMAP server for JUnit and Spring Boot tests: send, then assert on greenMail.getReceivedMessages()
Testcontainers start Mailpit from a test (see Testcontainers)

A good test verifies the recipient, subject, and that the HTML and plain parts exist, rather than comparing the whole raw message.

Production concerns

  • Authentication of your domain. Publish SPF, DKIM and DMARC records in DNS. Without them many providers put your mail in spam or reject it.
  • Use an email service. Amazon SES, SendGrid, Postmark and similar services give you SMTP credentials (or an HTTP API) and handle reputation, bounces and unsubscribes. Sending thousands of messages from your own server is a deliverability project of its own.
  • Header injection. Never put raw user input into headers. If a subject or address can contain a newline, an attacker can add Bcc: headers. Libraries validate addresses (InternetAddress.parse with strict mode), but do not build headers from strings yourself.
  • Do not leak data. Do not log full message bodies, and never email passwords. Send a time-limited reset link instead.
  • Handle failure. SMTP codes starting with 4 are temporary; retry with backoff. Codes starting with 5 are permanent: stop and record the address as invalid.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which port and mode is the usual choice for an application submitting mail to a provider?

    Port 587 is the submission port. The connection upgrades to TLS with STARTTLS before credentials are sent. Ports 110 and 143 are for reading mail.
  2. 2. What does multipart/alternative contain?

    The mail client picks the best alternative it can display. Attachments belong in multipart/mixed, and inline images in multipart/related.
  3. 3. Why is a message line that starts with a dot doubled in SMTP?

    The server treats a line with only a dot as the end of the DATA section. Dot-stuffing keeps real lines that begin with a dot from ending the message early.
  4. 4. In Spring, which call creates both a plain-text and an HTML body?

    setText(plain, html) builds a multipart/alternative. addInline attaches images referenced by cid, and SimpleMailMessage is plain text only.
  5. 5. How should email-sending code be arranged in a typical web request?

    SMTP is slow and can fail. Sending asynchronously after commit prevents mails about rolled-back work, and timeouts keep threads from hanging.

Summary

  • Email travels from your app to an SMTP submission server (port 587 with STARTTLS), which relays it to the recipient's server; IMAP/POP3 read mail.
  • SMTP is a text dialogue with success (2xx), temporary failure (4xx) and permanent failure (5xx) codes.
  • MIME structures messages: mixed (attachments), alternative (plain and HTML), related (inline images), with Base64 or quoted-printable encoding.
  • Jakarta Mail builds a MimeMessage from a Session and sends it with Transport; always set timeouts and read credentials from the environment.
  • Spring Boot offers JavaMailSender, SimpleMailMessage and MimeMessageHelper, configured through spring.mail.*; render bodies from templates and send asynchronously after commit.
  • Test with Mailpit or GreenMail, authenticate your domain with SPF, DKIM and DMARC, and never put unvalidated input into headers.

Next: Auditing and Soft Deletes with Hibernate Envers shows how to keep a history of changes to your data.