Hackforge Academy

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";
}

๐Ÿš€ Learn Spring Boot with real-world projects

๐Ÿ’ก Build REST APIs step by step

๐Ÿง  Improve backend development skills

๐ŸŽฏ Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

๐Ÿ

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
โš›๏ธ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
โ˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community