medium.com 1 min read Original Source

πŸš€ Sending OTP via Email using Spring Boot & Spring Mail

Email verification is a very common feature in web applications β€” whether it’s signing up for a new account, resetting a password, or enabling two-factor authentication. In this tutorial, we’ll learn how to send a One-Time Password (OTP) to a user’s email using Spring Boot and Spring Mail.

1️⃣ Add Dependencies

Add this dependency in your pom.xml:

<button data-code="
org.springframework.boot
spring-boot-starter-mail
” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2️⃣ Configure Mail Properties

In application.properties (or application.yml), configure your SMTP server.
(Here I’ll use Gmail SMTP as an example):

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username[email protected]
spring.mail.password=your-app-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username[email protected]
spring.mail.password=your-app-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

πŸ‘‰ Note: If you’re using Gmail, you’ll need to generate an App Password instead of using your Gmail password.

3️⃣ Create an OTP Generator

A simple utility to generate numeric OTPs:

<button data-code="import java.security.SecureRandom;

public class OtpUtil {
private static final SecureRandom random = new SecureRandom();

public static String generateOtp(int length) {
StringBuilder otp = new StringBuilder();
for (int i = 0; i

import java.security.SecureRandom;

public class OtpUtil {
    private static final SecureRandom random = new SecureRandom();

    public static String generateOtp(int length) {
        StringBuilder otp = new StringBuilder();
        for (int i = 0; i < length; i++) {
            otp.append(random.nextInt(10));
        }
        return otp.toString();
    }
}
import java.security.SecureRandom;

public class OtpUtil {
    private static final SecureRandom random = new SecureRandom();

    public static String generateOtp(int length) {
        StringBuilder otp = new StringBuilder();
        for (int i = 0; i < length; i++) {
            otp.append(random.nextInt(10));
        }
        return otp.toString();
    }
}

4️⃣ Service to Send Email

Now, let’s create a service that will generate the OTP and send it via email.

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 String sendOtpEmail(String toEmail) {
        String otp = OtpUtil.generateOtp(6); // 6-digit OTP

        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(toEmail);
        message.setSubject("Your OTP Code");
        message.setText("Your OTP is: " + otp + "nIt will expire in 5 minutes.");

        mailSender.send(message);

        return otp;
    }
}
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 String sendOtpEmail(String toEmail) {
        String otp = OtpUtil.generateOtp(6); // 6-digit OTP

        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(toEmail);
        message.setSubject("Your OTP Code");
        message.setText("Your OTP is: " + otp + "nIt will expire in 5 minutes.");

        mailSender.send(message);

        return otp;
    }
}

5️⃣ Create a REST API to Trigger OTP

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/otp")
public class OtpController {

    @Autowired
    private EmailService emailService;

    @PostMapping("/send")
    public String sendOtp(@RequestParam String email) {
        String otp = emailService.sendOtpEmail(email);
        return "OTP sent to " + email + " (for demo, OTP: " + otp + ")";
    }
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/otp")
public class OtpController {

    @Autowired
    private EmailService emailService;

    @PostMapping("/send")
    public String sendOtp(@RequestParam String email) {
        String otp = emailService.sendOtpEmail(email);
        return "OTP sent to " + email + " (for demo, OTP: " + otp + ")";
    }
}

6️⃣ Test the API

  • Start your Spring Boot application
  • Use Postman or cURL to send a request:

POST http://localhost:8080/api/otp/[email protected]
POST http://localhost:8080/api/otp/[email protected]

You should receive an email with the OTP. πŸŽ‰

7️⃣ What’s Next?

This is a basic implementation. In a real application, you should also:

  • Store OTPs in DB or cache (e.g., Redis) with expiry
  • Verify OTP on another API endpoint
  • Limit OTP requests to avoid spam

We just built a simple OTP email sender with Spring Boot and Spring Mail.
This feature can be extended for signup verification, password reset, or two-factor authentication.