Sending emails is a common requirement in modern web applications — for things like user registration, password resets, or notifications. In this tutorial, we’ll walk through how to send emails in a Spring Boot application using SMTP, specifically with Gmail’s SMTP server, and demonstrate how to send both plain emails and emails with attachments.
๐บ Video Demo
If you prefer watching over reading, here’s a full demo of this tutorial in action:
๐ GitHub Repo
Want the complete working code? Clone the GitHub link provided below which contains all the source code.
Source Code GitHub Link: https://github.com/TheDipDeveloper/Spring-Boot-Sending-Email
๐งฐ Prerequisites
-
Java 17 or above
-
Maven
-
Spring Boot 3.x
-
A Gmail account
๐ Step 1: Add Spring Boot Mail Dependency
First, add all the required dependency on pom.xml file
<dependencies>
<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>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
⚙️ Step 2: Configure SMTP in application.properties
Configure your SMTP settings in src/main/resources/application.properties
.
Here’s an example for Gmail:
spring.application.name=java-mail-service
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=emailId
spring.mail.password=16DigitAppPassword
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
๐ก Important: You’ll need to generate an App Password for your account.
๐ฆ Step 3: Create an Email Model
Create a simple class to hold the email request details.
package com.dipdeveloper.java_mail_service;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EmailDetails {
private String recipient;
private String msgBody;
private String subject;
private String attachment;
}
๐ง Step 4: Build the Email Service
Create a service interface:
package com.dipdeveloper.java_mail_service;
public interface EmailService {
String sendSimpleMail(EmailDetails details);
String sendMailWithAttachment(EmailDetails details);
}
Then implement it:
package com.dipdeveloper.java_mail_service;
import java.io.File;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
@Service
public class EmailServiceImpl implements EmailService {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String sender;
public String sendSimpleMail(EmailDetails details) {
try {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom(sender);
mailMessage.setTo(details.getRecipient());
mailMessage.setText(details.getMsgBody());
mailMessage.setSubject(details.getSubject());
javaMailSender.send(mailMessage);
return "Email Sent Successfully.";
} catch (Exception e) {
e.printStackTrace();
return "Error occur while Sending Mail";
}
}
public String sendMailWithAttachment(EmailDetails details) {
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setFrom(sender);
mimeMessageHelper.setTo(details.getRecipient());
mimeMessageHelper.setText(details.getMsgBody());
mimeMessageHelper.setSubject(details.getSubject());
FileSystemResource file = new FileSystemResource(new File(details.getAttachment()));
mimeMessageHelper.addAttachment(file.getFilename(), file);
javaMailSender.send(mimeMessage);
return "Email sent Successfully with Attachment.";
} catch (Exception e) {
e.printStackTrace();
return "Error occur while sending mail.";
}
}
}
๐ Step 5: Expose an API Endpoint
Now create a REST controller to trigger these emails.
package com.dipdeveloper.java_mail_service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmailController {
@Autowired
private EmailService emailService;
@PostMapping("/send")
public String sendMail(@RequestBody EmailDetails details) {
return emailService.sendSimpleMail(details);
}
@PostMapping("/sendWithAttachment")
public String sendMailWithAttachment(@RequestBody EmailDetails details) {
return emailService.sendMailWithAttachment(details);
}
}
๐งช Testing the API
You can use Postman or curl
to test the endpoints:
✅ Send Simple Email
https://github.com/TheDipDeveloper/Spring-Boot-Sending-Email/blob/main/README.md
✅ Send Email with Attachment
https://github.com/TheDipDeveloper/Spring-Boot-Sending-Email/blob/main/README.md
๐ฏ Conclusion
You’ve now built a Spring Boot application that can send both basic and attachment-based emails using SMTP. This is extremely useful for integrating email into your web apps — whether it’s for notifications, user onboarding, or customer support.
๐ Security Tip
Don’t hardcode your email credentials! Use Spring Cloud Config, Vault, or environment variables for production.
Comments
Post a Comment