Sending Emails Using Spring Boot
Sending emails is a common requirement in many applications — whether for user registration, password reset, notifications, or alerts. Spring Boot makes email integration simple using the JavaMailSender interface, which allows you to send both simple and complex emails effortlessly.
✅ Adding Dependencies
To get started, include the following dependency in your pom.xml (for Maven projects):
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
⚙️ Configuring Email Properties
In your application.properties or application.yml, configure your SMTP server details. For example, to use Gmail SMTP:
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.starttls.enable=true
⚠️ Note: For Gmail, you must generate an App Password (not your regular email password) if 2FA is enabled.
๐ค Sending a Simple Email
Create a service class to send emails:
@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;
public void sendSimpleEmail(String to, String subject, String body) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("your_email@gmail.com");
message.setTo(to);
message.setSubject(subject);
message.setText(body);
mailSender.send(message);
}
}
Use this service anywhere in your application:
emailService.sendSimpleEmail("recipient@example.com", "Test Subject", "Hello, this is a test email!");
๐ Sending Emails with Attachments (Optional)
For more complex needs, you can send emails with attachments using MimeMessageHelper:
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo("recipient@example.com");
helper.setSubject("Subject with Attachment");
helper.setText("Please find the attachment below.");
helper.addAttachment("file.txt", new File("path/to/file.txt"));
mailSender.send(message);
๐ก️ Best Practices
✅ Use environment variables to store sensitive email credentials.
✅ Avoid sending emails in the main thread — consider using @Async.
✅ Implement error handling for mail server downtime or invalid addresses.
๐ Conclusion
Spring Boot simplifies the process of sending emails using built-in support via JavaMailSender. Whether you're building a notification system or a user onboarding feature, email support can be added quickly and securely.
Let me know if you'd like to integrate HTML templates or schedule emails!
Learn MERN Stack Training Course
Understanding the useEffect Hook
JWT Authentication in Spring Boot
Scheduling Tasks with Spring Boot
Visit Our Quality Thought Training Institute
Comments
Post a Comment