Send OTP via SMS and Email using Azure Communication Services with Spring Boot


This guide will walk you through the entire process of setting up Azure Communication Services, integrating it with Spring Boot, and sending OTPs via both SMS and email.

1. Setting Up Azure Communication Services (ACS)

Step 1: Create an Azure Communication Services Resource

  1. Go to the Azure Portal → Search for Azure Communication Services → Click Create.
  2. Provide a name, subscription, resource group, and region.
  3. Click Review + Create, then Create.
  4. After the resource is created, go to the Keys section and copy the Connection String.
  5. Under Phone Numbers, purchase a phone number for sending SMS.

Step 2: Set Up Email in ACS

  1. Under Azure Communication Services, configure the Email feature in the portal by following the setup steps.

2. Set Up Spring Boot Project

Step 1: Create a Spring Boot Project

You can create a Spring Boot project using Spring Initializr (https://start.spring.io/):

  • Project: Maven Project
  • Language: Java
  • Spring Boot Version: 3.x.x or higher
  • Dependencies: Spring Web, Spring Boot DevTools

Alternatively, you can generate the project from the command line:

Step 2: Add Azure Communication Services Dependencies to pom.xml

<dependencies>
    <!-- Spring Boot Starter for web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Azure Communication Services SMS -->
    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-communication-sms</artifactId>
        <version>1.1.30</version>
    </dependency>

    <!-- Azure Communication Services Email -->
    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-communication-email</artifactId>
        <version>1.0.19</version>
    </dependency>
</dependencies>

Step 3: Add Application Properties

In src/main/resources/application.properties, add your Azure Communication Services connection details:

azure.communication.connectionString=<your_connection_string>
azure.communication.phoneNumber=<your_acs_phone_number>

3. Implementing the Service to Send OTPs

Step 1: Create the Azure Communication Service Class

Create a service class that uses ACS SDK to send SMS and Email.

import com.azure.communication.sms.SmsClient;
import com.azure.communication.sms.models.SmsSendResult;
import com.azure.communication.email.EmailClient;
import com.azure.communication.email.models.EmailMessage;
import com.azure.communication.email.models.EmailSendResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class AzureCommunicationService {

    @Value("${azure.communication.connectionString}")
    private String connectionString;

    @Value("${azure.communication.phoneNumber}")
    private String phoneNumber;

    // Send OTP via SMS
    public SmsSendResult sendOtpSms(String recipientPhoneNumber, String otpMessage) {
        SmsClient smsClient = new SmsClientBuilder()
                .connectionString(connectionString)
                .buildClient();

        SmsSendResult sendResult = smsClient.send(
                new SmsSendOptions(phoneNumber, recipientPhoneNumber, otpMessage)
        );
        return sendResult;
    }

    // Send OTP via Email
    public EmailSendResult sendOtpEmail(String recipientEmail, String otpMessage) {
        EmailClient emailClient = new EmailClientBuilder()
                .connectionString(connectionString)
                .buildClient();

        EmailMessage emailMessage = new EmailMessage()
                .setSender("your-email@example.com")
                .setRecipient(recipientEmail)
                .setSubject("Your OTP Code")
                .setBody(otpMessage);

        EmailSendResult emailSendResult = emailClient.send(emailMessage);
        return emailSendResult;
    }
}

Step 2: Create the OTP Controller

Create a controller to handle the HTTP request and trigger OTP sending via both SMS and Email.

import com.example.otp.service.AzureCommunicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

    @Autowired
    private AzureCommunicationService azureCommunicationService;

    @PostMapping("/send")
    public String sendOtp(@RequestParam String phoneNumber, @RequestParam String email) {
        String otp = generateOtp();
        String otpMessage = "Your OTP code is: " + otp;

        // Send OTP via SMS
        azureCommunicationService.sendOtpSms(phoneNumber, otpMessage);

        // Send OTP via Email
        azureCommunicationService.sendOtpEmail(email, otpMessage);

        return "OTP sent successfully!";
    }

    private String generateOtp() {
        // Generate a simple OTP here, for example:
        return String.valueOf((int) (Math.random() * 900000) + 100000);
    }
}

4. Testing the Application

Step 1: Run Your Spring Boot Application

Start your Spring Boot application by running:

./mvnw spring-boot:run

Step 2: Test the OTP API

You can use Postman or cURL to test the endpoint:

  • URL: http://localhost:8080/api/otp/send
  • Method: POST
  • Parameters:
    • phoneNumber: Phone number to send SMS OTP to.
    • email: Email address to send email OTP to.

Example Request (Postman):

POST http://localhost:8080/api/otp/send?phoneNumber=+11234567890&email=recipient@example.com

5. Summary of the Flow

  1. Azure Communication Services Setup: Create the ACS resource for both SMS and Email.
  2. Spring Boot Project Setup: Add the necessary ACS dependencies and configure them.
  3. OTP Service: The service generates and sends OTP via both SMS and email.
  4. Controller: Handles the endpoint to receive OTP requests and sends OTP to both mediums.

This complete solution will allow your Spring Boot application to send OTPs via both SMS and email using Azure Communication Services.

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example