Sending Simple and Attachment Mail in Spring Boot
In this tutorial, you will learn how to send emails from a Spring Boot
application — both simple plain-text messages and emails with file attachments.
The example uses JavaMailSender, SimpleMailMessage,
MimeMessageHelper, and Gmail's SMTP server.
By the end, you will have two working REST endpoints: one that sends a simple mail and
one that accepts a MultipartFile and attaches it to the outgoing email.
Project Structure
The Spring Boot project follows a simple layered structure:
SpringSendMailApplication.java
Standard Spring Boot entry point.
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringSendMailApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSendMailApplication.class, args);
}
}
SendController.java
Two REST endpoints are exposed. /sendSimpleMail sends a plain-text email
using SimpleMailMessage. /sendAttachMail sends an email with a
file attachment using MimeMessageHelper.
package com.example.demo.controller;
import java.io.File;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class SendController {
@Autowired
private JavaMailSender javaMailSender;
@PostMapping("/sendSimpleMail")
public String sendSimpleMail(@RequestParam String receiver,
@RequestParam String message,
@RequestParam String subject) {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setTo(receiver);
msg.setSubject(subject);
msg.setText(message);
javaMailSender.send(msg);
return "Send Message Successfully";
}
@PostMapping("/sendAttachMail")
public String sendAttachMail(@RequestParam String sender,
@RequestParam String receiver,
@RequestParam String msg,
@RequestParam String subject,
@RequestParam("file") MultipartFile file) throws Exception {
MimeMessage message = javaMailSender.createMimeMessage();
// true = multi-part message (required for attachments)
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(sender);
helper.setTo(receiver);
helper.setSubject(subject);
helper.setText(msg);
// Save MultipartFile to a temp file
String extension = file.getContentType().split("/")[1];
File tempFile = File.createTempFile("attachment", "." + extension);
file.transferTo(tempFile);
// Attach the temp file
helper.addAttachment(file.getOriginalFilename(), tempFile);
javaMailSender.send(message);
return "Send Message Successfully";
}
}
Key points about the attachment endpoint:
new MimeMessageHelper(message, true)— thetrueflag enables multi-part mode, required for attachments.File.createTempFile()— creates a safe temporary file for the upload before attaching it.helper.addAttachment(originalName, tempFile)— uses the original filename so the receiver sees a sensible name (not the temp one).
application.properties
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your-email@gmail.com
spring.mail.password=your-app-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000
spring.mail.properties.mail.smtp.starttls.enable=true
Property explanations:
spring.mail.host— SMTP server host. Gmail usessmtp.gmail.com.spring.mail.port— 587 for STARTTLS (recommended), 465 for SSL.spring.mail.username— your full Gmail address.spring.mail.password— NOT your Gmail password. Must be a 16-character App Password (see next section).starttls.enable=true— upgrades the connection to TLS after connecting.
Setting Up Gmail App Password
Google blocked "Less secure app access" in 2022. If you try to use your normal Gmail
password in spring.mail.password, you will get a
535 authentication error.
Correct setup steps:
- Go to Google Account → Security.
- Enable 2-Step Verification (required for App Passwords).
- Search for "App passwords" in your Google Account settings.
- Generate a new App Password — choose "Mail" and your device.
- Copy the 16-character password (no spaces) Google gives you.
- Paste it into
spring.mail.passwordinapplication.properties.
This is why you see a "Less secure app access" warning in the output screenshots — that option no longer exists. Use App Passwords instead.
pom.xml Dependencies
Add these two dependencies to your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
spring-boot-starter-mail brings in JavaMail and auto-configures
JavaMailSender. spring-boot-starter-web provides the REST
layer and MultipartFile support.
Output Screens
Below are the output screenshots from testing the endpoints:
How It Works (Step-by-Step)
-
Configure SMTP —
application.propertiestells Spring Boot where to send mail (Gmail SMTP) and how to authenticate. -
Auto-configure JavaMailSender — Spring Boot creates a
JavaMailSenderbean automatically becausespring-boot-starter-mailis on the classpath. -
Send simple mail —
POST /sendSimpleMailbuilds aSimpleMailMessagewith to, subject, and text; then callsjavaMailSender.send(). -
Send attachment mail —
POST /sendAttachMailcreates aMimeMessage, wraps it in aMimeMessageHelperwith multi-part enabled, saves theMultipartFileto a temp file, and attaches it viahelper.addAttachment(). -
Test with Postman — use form-data body with the expected fields
(
sender,receiver,subject,message/msg,file).
Customization Ideas
- Send HTML emails by using
helper.setText(html, true). - Add CC / BCC using
helper.setCc()andhelper.setBcc(). - Attach multiple files by calling
addAttachment()multiple times. - Use
@Asyncon the service method so mail sending does not block the request. - Move mail logic to a
MailServiceand keep the controller thin. - Switch to Thymeleaf templates for email body content.
Frequently Asked Questions
How do I send email in Spring Boot?
Add the spring-boot-starter-mail dependency, configure
spring.mail.* properties in application.properties, autowire
JavaMailSender, create a SimpleMailMessage for plain emails or
a MimeMessage with MimeMessageHelper for attachments, and call
javaMailSender.send().
How do I attach a file to an email in Spring Boot?
Use MimeMessageHelper with the multi-part constructor
new MimeMessageHelper(message, true). Save the MultipartFile to
a temporary File, then call
helper.addAttachment(fileName, file) before sending with
javaMailSender.send(message).
Why do I get a 535 authentication error when sending Gmail in Spring Boot?
Google no longer allows plain account passwords for SMTP. You must enable
2-Step Verification on your Google account, then generate a
16-character App Password at
myaccount.google.com/apppasswords.
Use that App Password in spring.mail.password instead of your real password.
What is the difference between SimpleMailMessage and MimeMessage?
SimpleMailMessage supports only plain-text emails (to, from, subject,
text). MimeMessage with MimeMessageHelper supports HTML
content, attachments, inline images, multiple recipients (to/cc/bcc), and custom
headers. Use MimeMessage for anything beyond plain text.
Which SMTP port should I use for Gmail in Spring Boot?
Use port 587 with STARTTLS
(spring.mail.properties.mail.smtp.starttls.enable=true) or port
465 with SSL. Port 587 with STARTTLS is the recommended option and is
what this tutorial uses.
Conclusion
In this tutorial, you built a working Spring Boot email service with two
endpoints — one for plain-text messages and one that supports file attachments. You used
JavaMailSender, SimpleMailMessage, and
MimeMessageHelper, and configured Gmail SMTP with a secure App Password.
This foundation works for most transactional email needs (notifications, alerts, invoices). For production-scale mail, consider Amazon SES, SendGrid, or Mailgun, and always run the send call asynchronously.
Related topics: Spring Boot @Async Email, Thymeleaf Email Templates, Spring Mail with HTML Content, Email Attachments with InputStreamSource, Gmail App Password Setup, SMTP over SSL vs STARTTLS
No comments:
Post a Comment