Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Configure Spring Boot to send an HTML email with an attachment using JavaMailSender and MimeMessageHelper. Which properties do you set, and how do you test it without a real SMTP server?

We add spring-boot-starter-mail and set spring.mail.host, port, username, password and spring.mail.properties.mail.smtp.auth and starttls.enable, and Boot auto-configures a JavaMailSender. To send, we create a MimeMessage, wrap it in new MimeMessageHelper(msg, true, "UTF-8") for multipart content, set the recipients, subject and HTML body with setText(html, true), add the attachment with addAttachment, and call send(). We set connection and read timeouts so a slow SMTP server cannot block threads, render HTML with a template engine such as Thymeleaf, and test with GreenMail or a Mailpit container, or with a mocked JavaMailSender in unit tests.

Why this question is asked

Sending email looks like a one-liner until the first HTML invoice arrives as raw tags, the attachment is missing, or a slow SMTP server freezes checkout. Interviewers ask this because it covers Boot auto-configuration, the MIME details that trip people up, and how to test something that talks to an external server. In this answer, we will configure the mail properties, build an HTML message with an attachment step by step, protect our threads with timeouts, render the HTML safely, and then test the whole thing at two levels.

1A Quick Recap: SMTP and JavaMailSender

Email is sent over SMTP, the protocol mail servers speak. Our application connects to an SMTP server, usually on port 587, upgrades the connection to TLS with the STARTTLS command, logs in, and hands over the message. JavaMailSender is Spring's interface for this, built on Jakarta Mail (formerly JavaMail; Boot 3 and later use the jakarta.mail packages).

A message with HTML and an attachment is a MIME multipart message: one email made of several parts, here an HTML body and a PDF file, each with its own content type. MimeMessageHelper is Spring's helper that builds those parts for us.

2Configuring the Properties

With spring-boot-starter-mail on the classpath and spring.mail.host set, Boot's MailSenderAutoConfiguration creates a JavaMailSenderImpl bean. Properties under spring.mail.properties are passed straight to Jakarta Mail, which is where TLS and timeouts are configured.

Properties
spring.mail.host=smtp.example.com
spring.mail.port=587
spring.mail.username=billing@example.com
spring.mail.password=${SMTP_PASSWORD} # from the environment or a secret store
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true # refuse to send in clear text
spring.mail.properties.mail.smtp.connectiontimeout=5000 # ms to open the connection
spring.mail.properties.mail.smtp.timeout=5000 # ms to wait for a read
spring.mail.properties.mail.smtp.writetimeout=5000 # ms to wait for a write

Notice the three timeouts. Jakarta Mail's defaults for them are infinite, so without these lines a hung SMTP server holds the sending thread forever. If emails are sent from request threads, a few minutes of SMTP trouble then exhausts the web server's thread pool, and the whole application stops answering.

3Building the HTML Message With an Attachment

Now we build the message. The second constructor argument, true, asks for a multipart message, which is required for attachments. The third sets the character encoding, so names like Muller with an umlaut or Japanese text arrive intact.

Java
@Service
class InvoiceMailer {
private final JavaMailSender mailSender;
private final SpringTemplateEngine templates;
InvoiceMailer(JavaMailSender mailSender, SpringTemplateEngine templates) {
this.mailSender = mailSender; this.templates = templates;
}
void sendInvoice(Customer c, Invoice inv, Resource pdf) throws MessagingException {
MimeMessage msg = mailSender.createMimeMessage();
MimeMessageHelper h = new MimeMessageHelper(msg, true, "UTF-8"); // multipart, UTF-8
h.setFrom("billing@example.com");
h.setTo(c.email());
h.setSubject("Your invoice " + inv.number());
Context ctx = new Context(c.locale());
ctx.setVariable("customer", c);
ctx.setVariable("invoice", inv);
String html = templates.process("mail/invoice", ctx); // templates/mail/invoice.html
h.setText(html, true); // true = this is HTML
h.addAttachment("invoice-" + inv.number() + ".pdf", pdf); // a Resource is an InputStreamSource
mailSender.send(msg); // MailException on failure
}
}
Step throughSending the invoice
InvoiceMailerThymeleafJavaMailSenderSMTP server
process("mail/invoice", ctx)
HTML with escaped values
send(multipart MimeMessage)
connect, STARTTLS, AUTH
DATA: HTML part + PDF part
250 OK

6 messages in order. Play them, or step through them one at a time.

Two details cause most bugs here. If we call setText(html) without true, the email shows the raw HTML tags as plain text. If we construct the helper without multipart = true, addAttachment throws an IllegalStateException telling us the message is not multipart. For clients that cannot show HTML, setText(plainText, html) sets both versions at once.

4Rendering HTML With a Template Engine

It is tempting to build the HTML with string concatenation, but that breaks in two ways. It is unreadable and hard to change, and it is unsafe: if a customer's name is <script>...</script> or contains a link, concatenation puts it into the email as live HTML. Thymeleaf's th:text escapes values automatically, so a name is always shown as text.

XML
<!-- templates/mail/invoice.html -->
<p>Hello <span th:text="${customer.name}">Name</span>,</p> <!-- escaped: &lt;b&gt; shows as text -->
<p>Your invoice <b th:text="${invoice.number}">INV-1</b> is attached.</p>
<p th:text="${#numbers.formatDecimal(invoice.total, 1, 2)}">0.00</p>

Templates also let designers and translators change the email without touching Java code, and the Context's locale lets the same template use the customer's language through message expressions.

5Testing Without a Real SMTP Server

We test at two levels. In unit tests, we mock JavaMailSender and capture the message to check its subject, recipients and parts. That is fast but does not prove the message is valid MIME or that our properties work.

In integration tests, we start a fake SMTP server that accepts mail and lets us read it. GreenMail runs inside the test JVM and has a JUnit 5 extension. Mailpit runs as a container through Testcontainers, accepts SMTP on port 1025 and offers an HTTP API on port 8025 to inspect what arrived. Either way we point spring.mail.host and port at it.

Java
@SpringBootTest
class InvoiceMailerIT {
@RegisterExtension
static GreenMailExtension smtp = new GreenMailExtension(ServerSetupTest.SMTP) // port 3025
.withConfiguration(GreenMailConfiguration.aConfig().withUser("billing@example.com", "secret"));
@DynamicPropertySource
static void mail(DynamicPropertyRegistry r) {
r.add("spring.mail.host", () -> "localhost");
r.add("spring.mail.port", () -> 3025);
r.add("spring.mail.username", () -> "billing@example.com");
r.add("spring.mail.password", () -> "secret");
r.add("spring.mail.properties.mail.smtp.starttls.enable", () -> "false"); // test server, no TLS
}
@Autowired InvoiceMailer mailer;
@Test
void sendsHtmlWithPdf() throws Exception {
mailer.sendInvoice(alice, invoice, new ClassPathResource("sample.pdf"));
MimeMessage[] got = smtp.getReceivedMessages();
assertThat(got).hasSize(1); // 1
assertThat(got[0].getSubject()).isEqualTo("Your invoice INV-7");
assertThat(GreenMailUtil.getBody(got[0])).contains("invoice-INV-7.pdf"); // attachment part present
}
}

Notice that the test disables STARTTLS, because the test server speaks plain SMTP. The production property file keeps it required.

6Follow-up questions

Should the email be sent on the request thread?

Usually not. Even with timeouts, SMTP can take hundreds of milliseconds, so the request should record that an email is needed and let an @Async method, a message consumer or an outbox worker send it. That also allows retries without making the user wait.

How do you embed an image instead of attaching it?

Use h.addInline("logo", resource) and reference it in the HTML as src="cid:logo". The inline part must be added after setText, because MimeMessageHelper attaches inline parts to the body that already exists.

What does Boot do if spring.mail.host is not set?

MailSenderAutoConfiguration is conditional on the host property (or a JNDI name), so no JavaMailSender bean is created and injecting one fails at startup. That is a useful signal in tests that forgot to configure mail.

7Conclusion

In this answer, we configured Boot's JavaMailSender with host, credentials, STARTTLS and three timeouts, built a multipart HTML message with MimeMessageHelper, setText(html, true) and addAttachment, rendered the body with Thymeleaf so user values are escaped, and tested it with a mocked sender for unit tests and GreenMail or Mailpit for integration tests.

What to say in the interviewAbout 70 seconds aloud

Open with

I'd add spring-boot-starter-mail and set spring.mail.host, port 587, username and a password from the environment, plus spring.mail.properties.mail.smtp.auth and starttls.enable set to true. With the host set, Boot auto-configures a JavaMailSender.

Then, if they want more

I'd also always set mail.smtp.connectiontimeout, timeout and writetimeout, because Jakarta Mail's defaults are infinite and a hung SMTP server would otherwise hold threads forever.

To send, I call mailSender.createMimeMessage(), wrap it in new MimeMessageHelper(msg, true, "UTF-8"), where true makes it multipart so attachments work, set from, to and subject, and call setText(html, true), where true marks the body as HTML; without it the tags show as text. Then addAttachment with a file name and a Resource, and mailSender.send(msg).

I don't build the HTML by concatenation; I render a Thymeleaf template, which escapes user values like names and lets us localise. For tests, unit tests mock JavaMailSender and capture the message.

Integration tests start GreenMail with its JUnit 5 extension, or a Mailpit container through Testcontainers, point spring.mail.host and port at it with @DynamicPropertySource, send the email, and assert on the received message, its subject and its attachment. And in production I'd send outside the request thread.

About this answer

Last updated
12 November 2026
Versions it names
JUnit 5
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Configure Spring Boot to send an HTML email with an attachment using JavaMailSender and...": https://scrivio-interview-library.netlify.app/spring-boot/spring-utilities/171b0d2354/