Category: spring_boot
how to send email in Spring Boot
Published on 26 Jun 2026
Explanation
Spring Boot provides built-in email support
through the JavaMailSender interface.
To send
emails, add the Spring Boot Mail
Starter dependency to the project.
Code:
<dependency>
<groupId>org.springframework.boot
</groupId>
<artifactId>spring-boot-starter-mail
</artifactId>
</dependency>
Explanation
Configure SMTP server details in the
application.properties file.
These settings allow Spring
Boot to connect to the email
provider and send messages.
Code:
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.starttls. enable=true
Explanation
Create a service class that uses
JavaMailSender to send emails.
The SimpleMailMessage
class is used for sending plain
text emails.
Code:
public void sendEmail(
String to, String subject, String body) {
SimpleMailMessage message =
new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(body);
mailSender.send(message);
}
}
Explanation
Expose a REST API endpoint that
accepts email details and delegates the
email-sending operation to the service layer.
Code:
@RestController
@RequestMapping("/email")
public class EmailController {
@Autowired
private EmailService emailService;
@PostMapping("/send")
public String sendEmail() {
emailService.sendEmail(
"student@gmail.com",
"Welcome",
"Welcome to Hackforge Academy"
);
return "Email Sent Successfully";
}
}
Explanation
For dynamic email requests, use @RequestBody
to receive recipient, subject, and message
content from the client application.
Code:
public record EmailRequest(
String to,
String subject,
String body
) {}
@PostMapping("/send")
public String sendEmail(
@RequestBody EmailRequest request) {
emailService.sendEmail(
request.to(),
request.subject(),
request.body()
);
return "Email Sent Successfully";
}