Spring Boot Tutorial
Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)
Prerequisite (Spring Core Concepts)
Spring Boot Core
Spring Boot with REST API
Spring Boot with Database and Data JPA
Spring Boot with Kafka
Spring Boot with AOP
Sending emails from a Spring Boot application is a common requirement, and Spring provides easy-to-use support for sending emails via SMTP using the JavaMailSender
interface. Here's a guide to help you send emails from a Spring Boot application:
Add the required dependencies to your pom.xml
:
<!-- Spring Boot Starter for Mail --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <!-- (Optional) Apache Commons Email for easier email composition --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-email</artifactId> <version>1.5</version> </dependency>
Configure your SMTP server details in application.properties
or application.yml
.
# SMTP server details spring.mail.host=smtp.example.com spring.mail.port=587 spring.mail.username=myemail@example.com spring.mail.password=mypassword # Additional properties spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true
Replace with your SMTP server details and credentials.
Create a service to send emails:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; @Service public class EmailService { @Autowired private JavaMailSender mailSender; public void sendSimpleEmail(String to, String subject, String text) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(text); mailSender.send(message); } }
If you want to send emails with attachments or HTML content, you'd use MimeMessage
instead of SimpleMailMessage
.
Now you can use the EmailService
to send an email:
@Autowired private EmailService emailService; public void someMethod() { emailService.sendSimpleEmail("recipient@example.com", "Test Subject", "This is a test email."); }
If you wish to send emails with attachments or HTML content, you would need to construct a MimeMessage
:
import org.springframework.mail.javamail.MimeMessageHelper; public void sendEmailWithAttachment(String to, String subject, String text, String pathToAttachment) { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setSubject(subject); helper.setText(text); FileSystemResource file = new FileSystemResource(new File(pathToAttachment)); helper.addAttachment("filename.txt", file); mailSender.send(message); }
Using Spring Boot to send emails is quite straightforward. The provided abstraction simplifies many complexities of sending emails, allowing developers to focus on the core functionality of their applications.
Configuring SMTP properties in Spring Boot:
application.properties
or application.yml
file to enable Spring Boot to send emails through an SMTP server.# SMTP configuration in application.properties spring.mail.host=smtp.example.com spring.mail.port=587 spring.mail.username=user@example.com spring.mail.password=secretpassword spring.mail.properties.mail.smtp.auth=true
Using JavaMailSender for email sending in Spring Boot:
JavaMailSender
interface. Autowire it in your service and use it to send emails.// Example using JavaMailSender in Spring Boot @Service public class EmailService { @Autowired private JavaMailSender javaMailSender; public void sendEmail(String to, String subject, String body) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(body); javaMailSender.send(message); } }
Sending HTML emails with Thymeleaf in Spring Boot:
// Example sending HTML email with Thymeleaf in Spring Boot @Service public class EmailService { @Autowired private JavaMailSender javaMailSender; @Autowired private TemplateEngine templateEngine; public void sendHtmlEmail(String to, String subject, Map<String, Object> model) { MimeMessage message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setSubject(subject); String htmlContent = templateEngine.process("email-template.html", new Context(Locale.getDefault(), model)); helper.setText(htmlContent, true); javaMailSender.send(message); } }
Attaching files to emails in Spring Boot with SMTP:
MimeMessageHelper
in Spring Boot. This is useful for sending documents or images as email attachments.// Example attaching files to email in Spring Boot @Service public class EmailService { @Autowired private JavaMailSender javaMailSender; public void sendEmailWithAttachment(String to, String subject, String body, String attachmentPath) { MimeMessage message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setSubject(subject); helper.setText(body); FileSystemResource file = new FileSystemResource(new File(attachmentPath)); helper.addAttachment("AttachmentName", file); javaMailSender.send(message); } }
Handling email templates and placeholders in Spring Boot:
<!-- Example Thymeleaf email template --> <p>Hello, [[${name}]]!</p>
Secure email communication with TLS and SSL in Spring Boot:
# TLS configuration in application.properties spring.mail.properties.mail.smtp.starttls.enable=true
Scheduling email tasks with Spring Boot:
@Scheduled
to send daily reports or reminders.// Example scheduling email task in Spring Boot @Service public class EmailService { @Autowired private JavaMailSender javaMailSender; @Scheduled(cron = "0 0 8 * * ?") // Run every day at 8 AM public void sendDailyReport() { // Task logic to send daily report email } }
Error handling and logging for email sending in Spring Boot:
// Example error handling and logging in Spring Boot email service @Service public class EmailService { private static final Logger logger = LoggerFactory.getLogger(EmailService.class); @Autowired private JavaMailSender javaMailSender; public void sendEmail(String to, String subject, String body) { try { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(body); javaMailSender.send(message); } catch (Exception e) { logger.error("Error sending email: {}", e.getMessage()); // Handle the error, e.g., send a notification or log it } } }