New guide: how to warm up a dedicated IP without hurting your reputation. Read now →
Log in
MigoSMTP
SMTP and APIUpdated 26 Oct 2026

Spring Boot Send Email with SMTP: JavaMailSender, HTML and Attachments

Configure Spring Boot mail for SMTP with spring.mail properties, send text, HTML and attachments with JavaMailSender and MimeMessageHelper, run sending asynchronously, test with GreenMail and fix common errors.

TK
Written by Tomasz Kowalski
Infrastructure and Reliability Engineer
Reviewed by Mateus Oliveira
  • Published23 Jun 2026
  • Read time8 min
  • Length1,549 words
Share this guide

Spring Boot makes email sending a matter of one dependency and a handful of properties. The mail starter pulls in Jakarta Mail and auto-configures a JavaMailSender bean from the spring.mail.* properties, so you inject it and send. The difficulty is not the first message but everything around it: the extra Jakarta Mail properties that turn on STARTTLS, the timeouts that stop a blocked port from hanging a request thread, HTML and attachments, running the work off the request thread and reading the exceptions Spring wraps around SMTP errors. This guide covers each of these with working examples. The values are placeholders. Take the real host, user name and password from your SMTP provider's dashboard and keep them out of the repository.

Starterspring-boot-starter-mail
Configspring.mail.* and spring.mail.properties.mail.smtp.*
SendSimpleMailMessage, or MimeMessage with MimeMessageHelper
Scale@Async or a queue, plus timeouts

Add the dependency

<!-- pom.xml -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

// build.gradle
implementation 'org.springframework.boot:spring-boot-starter-mail'

Configure the connection

Spring Boot reads the connection from application.properties or application.yml. Anything under spring.mail.properties is passed to Jakarta Mail unchanged, which is where the encryption and timeout settings go.

# application.properties
spring.mail.host=smtp.example.com
spring.mail.port=587
spring.mail.username=${SMTP_USER}
spring.mail.password=${SMTP_PASSWORD}

spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.connectiontimeout=10000
spring.mail.properties.mail.smtp.timeout=20000
spring.mail.properties.mail.smtp.writetimeout=20000

The placeholders ${SMTP_USER} and ${SMTP_PASSWORD} read environment variables, which keeps secrets out of the file. Setting starttls.required=true makes the connection fail if the server does not offer encryption, instead of continuing in clear text, and that is what you want when a password is involved. The three timeout properties are in milliseconds. Without them, the Jakarta Mail defaults are effectively unlimited, and a blocked outbound port can hold a thread indefinitely.

For implicit TLS on port 465, replace the STARTTLS lines with spring.mail.port=465 and spring.mail.properties.mail.smtp.ssl.enable=true. Do not combine ssl.enable with port 587, and do not combine STARTTLS with port 465; the mismatch causes handshake errors. If you are unsure which port to choose, read which SMTP port to use.

Send a simple text message

Inject JavaMailSender and use SimpleMailMessage for plain text.

@Service
public class MailService {

    private final JavaMailSender sender;

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

    public void sendPlain(String to, String subject, String text) {
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom("[email protected]");
        msg.setTo(to);
        msg.setSubject(subject);
        msg.setText(text);
        sender.send(msg);
    }
}

The From address must belong to a domain you have authenticated with your provider, otherwise the server may refuse it or recipients may distrust it. The guide on authenticating your sending domain explains the records.

Send HTML with an attachment

For HTML and files, build a MimeMessage and let MimeMessageHelper do the multipart work. Pass true for multipart and name the encoding explicitly.

public void sendOrder(String to, String name, byte[] pdf) throws MessagingException {
    MimeMessage message = sender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

    helper.setFrom("[email protected]", "Example App");
    helper.setTo(to);
    helper.setReplyTo("[email protected]");
    helper.setSubject("Your order has shipped");

    String text = "Hi " + name + ", your order has shipped.";
    String html = "<p>Hi " + HtmlUtils.htmlEscape(name) + ",</p><p>Your order has shipped.</p>";
    helper.setText(text, html);                 // plain text first, HTML second

    helper.addAttachment("invoice.pdf", new ByteArrayResource(pdf), "application/pdf");

    sender.send(message);
}

Two details matter. The two-argument form of setText(text, html) creates a multipart/alternative body with both parts, which improves compatibility and is trusted more by filters than HTML alone. And values that come from users must be escaped before you put them in HTML; HtmlUtils.htmlEscape from Spring handles that. Note that setFrom with a display name throws UnsupportedEncodingException, so declare it or catch it.

Render templates with Thymeleaf

Building HTML with string concatenation does not scale. Add the Thymeleaf starter, keep templates under src/main/resources/templates/mail/, and render them with the TemplateEngine. Render a text template as well, so both parts come from the same model. Use inline styles and simple tables, because many email clients ignore external CSS. The HTML email template guide lists what renders reliably.

Context ctx = new Context();
ctx.setVariable("name", name);
String html = templateEngine.process("mail/order-shipped.html", ctx);
String text = templateEngine.process("mail/order-shipped.txt", ctx);
helper.setText(text, html);

Do not block request threads

An SMTP conversation can take seconds, and a failing server can take as long as your timeout. Sending inside a controller method holds a request thread for that time. There are three escalating options. The simplest is @Async with @EnableAsync on a configuration class and a bounded ThreadPoolTaskExecutor, so sends run on a separate pool and a flood of requests cannot create unlimited threads. The next is to write an outbox row to your database in the same transaction as the business change, and let a scheduled worker send pending rows, marking each as sent or failed. That survives restarts and gives you a record of what happened. The most robust is a message broker with a consumer that sends. In every case, make the operation safe to retry and separate temporary failures from permanent ones using the approach in rate limits, retries and backoff.

Use more than one account

The auto-configured bean covers the common case of a single account. If transactional and marketing mail must use different accounts, define your own beans and give them qualifiers. Create a JavaMailSenderImpl, set the host, port, user name, password and a Properties object with the same mail.smtp.* keys, and expose it with @Bean("transactionalSender"). Inject it with @Qualifier where needed. Declaring your own JavaMailSender bean makes Boot back off from creating the default one, so be explicit about which bean each service receives. Keeping the two streams on separate accounts and, ideally, separate sending subdomains means that a complaint spike from a campaign cannot delay a password reset.

Profiles and safe defaults

Use Spring profiles so that development and test never reach a real mail server. In the dev profile point spring.mail.host at a local catcher, and in the test profile use GreenMail. In staging, add a guard in your mail service that replaces the recipient with a test address unless the domain is on an allow-list, because staging databases are often copies of production data and one careless test run can email real customers. Record the profile name in the subject line of non-production mail so nobody confuses a test message with a real one.

Finally, keep an eye on limits. Providers cap the number of messages per second and per day, and they respond to bursts with temporary failures. Send through a bounded pool, honour the retry guidance in the replies, and validate addresses before sending so you do not waste capacity or damage your reputation on addresses that cannot receive mail. The guide on email validation before sending lists useful checks.

Understand the exceptions

Spring wraps Jakarta Mail errors in its own hierarchy under org.springframework.mail. MailAuthenticationException means the login failed. MailSendException means the send failed, and its getFailedMessages() and cause show which messages and why. MailParseException means the message could not be built. Read the root cause with getMostSpecificCause(): it holds the server reply, such as a 535 or a 550, that tells you what to fix. Log the status line and the recipient domain, not the password and not the full message body.

SymptomLikely causeFix
MailAuthenticationException with 535Wrong credentials or an unset environment variablePrint whether the variables are set (not their values) and re-copy them; see SMTP error 535
MailSendException: Couldn't connect to hostWrong host or port, or outbound SMTP blockedTest from the same host with the steps in how to test an SMTP connection
SSLHandshakeException or "Unrecognized SSL message"TLS mode does not match the portUse STARTTLS with 587 and SSL with 465
Request hangs for a long timeNo timeouts setSet connection, read and write timeouts
MailSendException 550 sender rejectedFrom address is not on a verified domainSend from an authenticated domain
Accepted but lands in spamMissing authentication or poor reputationUse the spam checklist

Test without a real server

Unit tests should mock JavaMailSender and verify that send was called with the right message. For integration tests, GreenMail runs an in-process SMTP server that stores received messages so you can assert on their subject, recipients and body. Run it on a random port and point spring.mail.host and spring.mail.port at it in the test configuration. In development, a local mail catcher in a container lets you see rendered messages without sending any. You can set spring.mail.test-connection=true to make the application check the connection at startup, but think before enabling it in production, since a temporary mail outage would then prevent the application from starting.

Use Spring Boot with a managed SMTP relay Point spring.mail at the host in your dashboard and send your first message in minutes.

Explore the SMTP relay

References and further reading

Frequently asked questions

Which properties turn on STARTTLS in Spring Boot?

Set spring.mail.properties.mail.smtp.starttls.enable=true and, to avoid a clear-text fallback, spring.mail.properties.mail.smtp.starttls.required=true, with port 587.

How do I send HTML email with Spring Boot?

Create a MimeMessage, wrap it in MimeMessageHelper with multipart true, and call setText with both the plain text and the HTML.

Why does my Spring Boot request hang when sending email?

No timeouts are set, so a blocked port holds the thread. Set the connection, read and write timeouts, and send asynchronously.

How can I test email in Spring Boot?

Mock JavaMailSender in unit tests and use GreenMail as an in-process SMTP server for integration tests.

What does MailAuthenticationException mean?

The SMTP login failed. Check the user name and password, that environment variables are set, and that the account is allowed to use SMTP.

Topics#java#spring boot#javamail#smtp#developers
Was this guide helpful?Your answer helps us improve our documentation.

Start sending in minutes.

Create an account, add your domain and send your first email.

Get started Talk to sales