Skip to main content

How to Send Emails in Spring Boot Using SMTP (With and Without Attachments)

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.

How to Send Emails in Spring Boot Using SMTP (With and Without 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

Popular posts from this blog

25+ Spring Data JPA Interview Questions with Answers, Explanations & Use Cases

  ๐Ÿ“˜ Spring Data JPA Interview Questions (with Answers, Explanations & Use Cases) 1. What is JPA and how is it related to Spring Data JPA? Answer: JPA (Java Persistence API) is a Java specification for managing relational data. Spring Data JPA is a part of Spring Data that simplifies JPA usage by reducing boilerplate code. Use Case: Persisting Java objects (like User ) to a relational database without writing SQL. 2. What are the key annotations used in JPA? Answer: @Entity , @Table , @Id , @GeneratedValue , @Column , @ManyToOne , @OneToMany , etc. Explanation: These annotations map Java objects to database tables and relationships. Use Case: Creating a User entity with an auto-generated ID and fields mapped to table columns. 3. What is the difference between JPA and Hibernate? Answer: JPA is a specification; Hibernate is an implementation of that specification. Use Case: Using Hibernate as the default JPA provider in Spring Boot. 4. How do you define a p...

Create a Real-World Banking System with Spring Boot 3, JPA, MySQL & Postman

Are you looking to build a real-world project using Spring Boot and MySQL? In this tutorial, we'll walk you through creating a complete Banking Service REST API that supports full CRUD operations, money transfers, deposits, and withdrawals. Whether you're preparing for interviews or enhancing your portfolio, this hands-on project will give you practical experience with Spring Boot 3, Spring Data JPA, and RESTful API design. In this post, you'll learn how to build a Banking Service REST API using: ✅ Spring Boot 3.x ✅ Java 17 ✅ MySQL ✅ Postman for API testing ✅ IntelliJ IDEA ✅ GitHub Repo : https://github.com/TheDipDeveloper/Banking-Service-Application-REST-Api By the end, you'll have a complete backend application that supports: Creating bank accounts Fetching account data Deposits and withdrawals Transferring funds between accounts Deleting accounts ๐Ÿ› ️ Tech Stack Java 17 Spring Boot 3.x Spring Data JPA MySQL Lombok ...