To send email in Spring Boot, add spring-boot-starter-mail, set the spring.mail.* properties for your SMTP server, and inject JavaMailSender. Use SimpleMailMessage for plain text and MimeMessage with MimeMessageHelper for HTML and attachments. Spring Boot auto-configures the sender once spring.mail.host is set, so you do not define the bean yourself.
This guide gives a complete configuration for STARTTLS on port 587 and implicit TLS on port 465, working code for text, HTML and attachments, Thymeleaf templates, asynchronous sending, error handling and a troubleshooting table. The underlying library is Jakarta Mail; its properties are explained in sending email with Jakarta Mail.
Add the dependency
<!-- Maven -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
// Gradle
implementation 'org.springframework.boot:spring-boot-starter-mail'The starter brings in Spring's mail support and the Jakarta Mail implementation. Spring Boot 3 and later use the jakarta.mail namespace; Boot 2 used javax.mail. Use the version managed by your Boot release rather than pinning one yourself.
Configure the SMTP server
# application.properties : STARTTLS on port 587
spring.mail.host=${SMTP_HOST}
spring.mail.port=587
spring.mail.username=${SMTP_USER}
spring.mail.password=${SMTP_PASS}
spring.mail.default-encoding=UTF-8
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.ssl.checkserveridentity=true
spring.mail.properties.mail.smtp.connectiontimeout=15000
spring.mail.properties.mail.smtp.timeout=30000
spring.mail.properties.mail.smtp.writetimeout=30000# application.properties : implicit TLS on port 465
spring.mail.host=${SMTP_HOST}
spring.mail.port=465
spring.mail.username=${SMTP_USER}
spring.mail.password=${SMTP_PASS}
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.smtp.ssl.checkserveridentity=true
spring.mail.properties.mail.smtp.connectiontimeout=15000
spring.mail.properties.mail.smtp.timeout=30000
spring.mail.properties.mail.smtp.writetimeout=30000Placeholders such as ${SMTP_PASS} read environment variables, so secrets stay out of the file. Do not enable both STARTTLS and SSL for the same connection. Property names under spring.mail.properties are passed straight to Jakarta Mail, which is why they carry the mail.smtp prefix. Choosing the right port and mode is covered in SMTP settings, ports and authentication. The same settings in YAML use nested keys under spring.mail.properties.mail.smtp.
| Property | Purpose |
|---|---|
| spring.mail.host / port | Server name and port |
| spring.mail.username / password | Authentication credentials |
| spring.mail.protocol | Defaults to smtp; smtps is rarely needed when ssl.enable is used |
| spring.mail.default-encoding | Charset for message text, UTF-8 recommended |
| spring.mail.test-connection | If true, verifies the connection at startup |
| mail.smtp.starttls.enable and required | Upgrade to TLS on 587 and refuse to continue without it |
| mail.smtp.ssl.enable | TLS from connect, for 465 |
| mail.smtp.*timeout | Connection, read and write timeouts in milliseconds |
Send a plain-text message
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class MailService {
private final JavaMailSender mailSender;
public MailService(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void sendText(String to, String subject, String body) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("[email protected]");
message.setTo(to);
message.setSubject(subject);
message.setText(body);
mailSender.send(message);
}
}Constructor injection keeps the service easy to test. The From address must be an address your server permits and on a domain you have authenticated; see authenticating your sending domain.
Send HTML with an attachment
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.MimeMessageHelper;
import java.io.File;
public void sendHtml(String to, String subject, String plain, String html, File pdf)
throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); // true = multipart
helper.setFrom("[email protected]");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(plain, html); // plain text and HTML alternatives
helper.addAttachment("invoice.pdf", new FileSystemResource(pdf));
mailSender.send(message);
}The second constructor argument true enables multipart mode, which is required for attachments and inline content. Passing both strings to setText(plain, html) creates a multipart/alternative body, so clients that cannot or will not render HTML still show a readable message. To embed an image referenced from the HTML as cid:logo, call helper.addInline("logo", resource) after setText. Message size limits and base64 overhead are explained in base64 overhead.
Render templates with Thymeleaf
<!-- build.gradle or pom: add spring-boot-starter-thymeleaf -->
// src/main/resources/templates/email/welcome.html
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1 th:text="'Welcome, ' + ${name}">Welcome</h1>
<p>Your account is ready. <a th:href="${url}">Sign in</a></p>
</body>
</html>
// Java
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
Context ctx = new Context();
ctx.setVariable("name", "Asha");
ctx.setVariable("url", "https://example.com/signin");
String html = templateEngine.process("email/welcome", ctx);Inject the auto-configured TemplateEngine and pass the rendered string to helper.setText(plain, html). Thymeleaf escapes variables by default, which protects against injecting markup from user data. Write a matching plain-text version of every template, and test the HTML in real clients, since email supports much less CSS than browsers; see email CSS support. Version and localise templates deliberately; see template versioning.
Send asynchronously
@Configuration
@EnableAsync
class AsyncConfig {}
@Service
public class NotificationService {
private final MailService mailService;
public NotificationService(MailService mailService) { this.mailService = mailService; }
@Async
public void welcome(String to, String name) {
mailService.sendWelcome(to, name); // runs on a task executor thread
}
}An SMTP call can take seconds or fail, and you rarely want a user's HTTP request to wait for it. @Async moves the work to a task executor, but it still loses messages if the application restarts mid-send and it has no retry. For anything important, store the message in a database table or put it on a queue and let a worker send it with retries and a record of the outcome. Design guidance is in reliable email sending design. Configure the executor pool size to match the connection limits your provider allows.
Error handling
try {
mailSender.send(message);
} catch (MailAuthenticationException e) {
log.error("SMTP authentication failed", e); // 535: credentials or policy
} catch (MailSendException e) {
log.error("Send failed: {}", e.getFailedMessages()); // server rejected message or recipients
} catch (MailException e) {
log.error("Mail error", e); // connection and other problems
}Spring wraps Jakarta Mail exceptions in its unchecked MailException hierarchy. Check the cause for socket and TLS problems. Treat temporary 4xx replies as retryable and permanent 5xx as final.
Configuration per environment
Keep the production credentials out of the repository and let each environment supply its own. In development, point spring.mail.host at a local catch-all SMTP server so no real recipient ever receives test mail. Tools such as Mailpit or MailHog accept any message on a local port and show it in a web page, and the GreenMail library offers an in-process server for integration tests. Use Spring profiles to switch: a dev profile with host localhost and a high port without authentication, a staging profile that sends only to an allow-listed set of test addresses, and a prod profile that reads secrets from the environment or a secrets manager. Setting spring.mail.test-connection=true in production makes a wrong host or password fail at startup rather than at the first customer email. Staging design is covered in testing email in staging.
Use more than one mail account
Auto-configuration gives you one JavaMailSender. Applications that must send transactional mail and marketing mail through different accounts, which is good practice because it separates their reputations, can define their own beans and qualify them.
@Configuration
class MailConfig {
@Bean
@Primary
JavaMailSender transactionalSender(@Value("${mail.tx.host}") String host,
@Value("${mail.tx.user}") String user,
@Value("${mail.tx.pass}") String pass) {
JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost(host);
sender.setPort(587);
sender.setUsername(user);
sender.setPassword(pass);
sender.setDefaultEncoding("UTF-8");
Properties p = sender.getJavaMailProperties();
p.put("mail.smtp.auth", "true");
p.put("mail.smtp.starttls.enable", "true");
p.put("mail.smtp.starttls.required", "true");
p.put("mail.smtp.connectiontimeout", "15000");
p.put("mail.smtp.timeout", "30000");
p.put("mail.smtp.writetimeout", "30000");
return sender;
}
}Defining your own JavaMailSender bean makes the auto-configuration back off, so repeat the timeout and TLS properties there. Inject the second sender with @Qualifier. Separating streams is discussed in separating transactional and marketing streams.
Deliverability basics for application mail
- Authenticate the sending domain with SPF, DKIM and DMARC before launch; unauthenticated mail from a new application is the most common reason for spam placement.
- Use a stable From address on your own domain and a monitored Reply-To. Do not set the From address to a user-supplied value.
- Send a text part with every HTML message and keep templates small and valid.
- Handle bounces: stop mailing addresses that hard bounce. SMTP acceptance is not delivery.
- Add unsubscribe handling to anything that is not strictly transactional.
Logging and observability
Log one structured line per send attempt with a correlation id from your own domain (an order or user id), the recipient domain rather than the full address if privacy rules require it, the template name, the outcome and, on failure, the exception class and the SMTP reply text. Avoid logging message bodies or credentials. Enable Jakarta Mail debug output only when reproducing a fault, using spring.mail.properties.mail.debug=true in a non-production profile, because the output includes the full SMTP dialogue. Expose counters for sent, failed and retried messages through your metrics library so that a sudden rise in failures raises an alert before customers write in. Remember that a successful send() only proves the server accepted the message; track bounces and complaints separately, through the provider's webhooks or its dashboard, and feed them back into a suppression list.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| MailAuthenticationException | Wrong credentials, or an app password or API key is required | Verify with another client. See error 535 |
| Mail server connection failed, timeout | Port blocked, wrong host or TLS mismatch | Match 587 with STARTTLS and 465 with ssl.enable; set timeouts |
| SSLHandshakeException: PKIX path building failed | Issuer not in the Java trust store | Install the CA certificate; do not disable verification |
| NoSuchBeanDefinition for JavaMailSender | spring.mail.host not set, or starter missing | Set the host and add the starter |
| Works in dev, fails in the container | Environment variables missing or outbound port blocked | Check variables and egress rules |
| Message accepted but in spam | Unauthenticated domain or content issues | Set up SPF, DKIM and DMARC |
Next steps
Start with the text example against a test mailbox, add HTML and a template, then move sending to a queue-backed worker. Keep one mail service class so the rest of the code never depends on mail details, and write tests against it with a mock JavaMailSender. If you send through MigoSMTP, use smtp.migosmtp.com with port 587 (STARTTLS) or 465 (implicit TLS) in the properties above. For an HTTP alternative to SMTP, compare the models in SMTP versus API.
Send Spring Boot mail through a managed relay Use authenticated SMTP with delivery events for your application.
References and further reading
Frequently asked questions
How do I send email in Spring Boot?
Add spring-boot-starter-mail, set the spring.mail properties, inject JavaMailSender and call send() with a SimpleMailMessage or MimeMessage.
What are the Spring Boot SMTP properties for port 587?
Set spring.mail.host, port 587, username and password, plus mail.smtp.auth, mail.smtp.starttls.enable and mail.smtp.starttls.required under spring.mail.properties.
How do I send an HTML email with an attachment?
Create a MimeMessage with MimeMessageHelper in multipart mode, call setText(plain, html) and addAttachment() with a resource.
Why does JavaMailSender hang or time out?
The Jakarta Mail timeouts are infinite by default. Set mail.smtp.connectiontimeout, timeout and writetimeout, and check that the port is not blocked.
Should I send email inside the request thread?
No. Send asynchronously or from a queue worker so slow or failing SMTP calls do not block users, and add retries for temporary failures.