How to Send SMS Using Vonage(formerly Nexmo) API in Spring Boot Application

Here’s an example of how to send an SMS using the Vonage (formerly Nexmo) SMS API in a Spring Boot application:

1. Create a Vonage Account

Before integrating Vonage into your Spring Boot application, you need to create an account and get your API credentials.

  • Sign up for a Vonage account at https://dashboard.nexmo.com/.
  • After signing up, obtain your API key and API secret from the Vonage dashboard.

2. Add Dependencies

To use the Vonage SDK in your Spring Boot project, include the following dependency in your pom.xml file. 

<dependency>
    <groupId>com.vonage</groupId>
    <artifactId>server-sdk</artifactId>
    <version>8.15.1</version>
</dependency>

Note: If you’re using the client artifact (previously com.vonage.client), replace the artifact with the updated server-sdk version as per the migration.


3. Vonage API Configuration

Next, create a configuration class to set up the Vonage client with your API credentials. This class will enable your Spring Boot application to interact with the Vonage API.

import com.vonage.client.VonageClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class VonageConfig {

    @Bean
    public VonageClient vonageClient() {
        return VonageClient.builder()
                .apiKey("your_api_key")  // Replace with your actual API key
                .apiSecret("your_api_secret")  // Replace with your actual API secret
                .build();
    }
}

Tip: Make sure to store your API key and API secret securely (e.g., in environment variables).


4. SMS Service

Create a service that will handle sending SMS messages using the Vonage API.

import com.vonage.client.VonageClient;
import com.vonage.client.sms.SmsSubmissionResponse;
import com.vonage.client.sms.SmsSubmissionResponseMessage;
import org.springframework.stereotype.Service;

@Service
public class SmsService {

    private final VonageClient vonageClient;

    public SmsService(VonageClient vonageClient) {
        this.vonageClient = vonageClient;
    }

    public void sendSms(String from, String to, String text) {
        try {
            SmsSubmissionResponse response = vonageClient.getSmsClient().submitMessage(
                new com.vonage.client.sms.Message(from, to, text)
            );

            for (SmsSubmissionResponseMessage message : response.getMessages()) {
                if (message.getStatus() == SmsSubmissionResponseMessage.Status.OK) {
                    System.out.println("Message sent successfully. Message ID: " + message.getMessageId());
                } else {
                    System.err.println("Message failed with error: " + message.getErrorText());
                }
            }
        } catch (Exception e) {
            System.err.println("Failed to send SMS: " + e.getMessage());
        }
    }
}

5. Controller

Create a REST controller that will expose an endpoint to trigger the SMS sending process. The controller will accept to (recipient's phone number) and text (message content) as parameters.

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/sms")
public class SmsController {

    private final SmsService smsService;

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

    @PostMapping("/send")
    public String sendSms(@RequestParam String to, @RequestParam String text) {
        String from = "VonageSMS";  // Replace with your sender ID or phone number
        smsService.sendSms(from, to, text);
        return "SMS sent to " + to;
    }
}

6. Run the Application

Once your Spring Boot application is set up, run it. You can test the SMS sending feature by using a tool like Postman or directly via your browser to send a POST request to the following endpoint:

POST http://localhost:8080/api/sms/send

Parameters:

  • to: The recipient's phone number (e.g., +1234567890).
  • text: The message text you want to send.

Example body for Postman:

{
  "to": "+1234567890",
  "text": "Hello, this is a test message from Vonage!"
}

7. Testing and Logs

Once you send the SMS, check the application logs to confirm whether the message was sent successfully or if an error occurred. If successful, you will see a log message like:

Message sent successfully. Message ID: [message_id]

If there’s an error, the log will show details like:

Message failed with error: [error_text]

Notes:

  • Secure API Credentials: Ensure that your API key and API secret are securely stored, preferably in environment variables.
  • Sender ID: Replace VonageSMS with your actual sender ID (if you want to use a custom sender ID). Note that some countries support custom sender IDs.
  • Free Credits: Vonage offers free credits upon signup. Use them to test the functionality of your integration.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete