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.
Note: If you’re using the
client
artifact (previouslycom.vonage.client
), replace the artifact with the updatedserver-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.
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.
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.
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:
Parameters:
to
: The recipient's phone number (e.g.,+1234567890
).text
: The message text you want to send.
Example body for Postman:
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:
If there’s an error, the log will show details like:
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.