CODE WITH SIBIN

Solving Real Problems with Real Code


Sending SMS with Spring Boot and Azure Communication Services

This guide will walk you through setting up SMS functionality in a Spring Boot application using Azure Communication Services.

Prerequisites

  • Azure account with an active subscription
  • Java Development Kit (JDK) 8 or later
  • Maven or Gradle build tool
  • Spring Boot 2.5+ or 3.x

Step 1: Set up Azure Communication Services

  1. Log in to the Azure Portal
  2. Create a new "Communication Services" resource
  3. Note your connection string and phone number from the resource overview

Step 2: Add Dependencies

Maven Configuration

Add the Azure SDK Bill of Materials (BOM) and SMS dependency to your pom.xml:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-sdk-bom</artifactId>
            <version>1.2.15</version> <!-- Use latest version -->
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-communication-sms</artifactId>
    </dependency>
    <!-- Spring Boot dependencies as needed -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

Step 3: Configure Azure Properties

Add these to your application.properties or application.yml:

# Azure Communication Services Configuration
azure.communication.connection-string=your-connection-string
azure.communication.sender-phone-number=+1234567890

Step 4: Create Configuration Class

import com.azure.communication.sms.SmsClient;
import com.azure.communication.sms.SmsClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AzureSmsConfig {
    
    @Value("${azure.communication.connection-string}")
    private String connectionString;
    
    @Value("${azure.communication.sender-phone-number}")
    private String senderPhoneNumber;
    
    @Bean
    public SmsClient smsClient() {
        return new SmsClientBuilder()
                .connectionString(connectionString)
                .buildClient();
    }
    
    @Bean
    public String senderPhoneNumber() {
        return senderPhoneNumber;
    }
}

Step 5: Create SMS Service

import com.azure.communication.sms.SmsClient;
import com.azure.communication.sms.models.SmsSendResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SmsService {

    private final SmsClient smsClient;
    private final String senderPhoneNumber;

    @Autowired
    public SmsService(SmsClient smsClient, String senderPhoneNumber) {
        this.smsClient = smsClient;
        this.senderPhoneNumber = senderPhoneNumber;
    }

    public String sendSms(String toPhoneNumber, String message) {
        List<String> toNumbers = new ArrayList<>();
        toNumbers.add(toPhoneNumber);

        SmsSendResult sendResult = smsClient.sendMessage(
                senderPhoneNumber,
                toNumbers,
                message);

        return "Message ID: " + sendResult.getMessageId() + 
               " Status: " + sendResult.getSuccessful();
    }
}

Step 6: Create REST Controller

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SmsController {

    private final SmsService smsService;

    @Autowired
    public SmsController(SmsService smsService) {
        this.smsService = smsService;
    }

    @PostMapping("/send-sms")
    public String sendSms(
            @RequestParam String phoneNumber,
            @RequestParam String message) {
        return smsService.sendSms(phoneNumber, message);
    }
}

Step 7: Test the Application

  1. Start your Spring Boot application
  2. Send a POST request to /send-sms with parameters:
    • phoneNumber: The recipient's phone number in E.164 format (e.g., +15551234567)
    • message: The text message to send

Example using curl:

curl -X POST "http://localhost:8080/send-sms?phoneNumber=%2B15551234567&message=Hello%20from%20Spring%20Boot"

Additional Considerations

  1. Error Handling: Add proper exception handling for Azure SDK exceptions
  2. Async Support: Consider making the SMS sending asynchronous
  3. Phone Number Validation: Validate phone numbers before sending
  4. Rate Limiting: Be aware of Azure Communication Services rate limits
  5. Security: Secure your SMS endpoint with authentication

Troubleshooting

  • Verify your connection string is correct
  • Ensure your phone number is properly formatted (E.164 format)
  • Check that your Azure Communication Services resource has SMS capability enabled
  • Verify you have sufficient credit in your Azure account

This implementation provides a basic but complete integration of Azure Communication Services SMS capabilities with Spring Boot. You can extend it with additional features like delivery reports, message templates, or bulk sending as needed.

Leave a Reply

Your email address will not be published. Required fields are marked *