Send SMS with Twilio using Spring Boot

Senura Vihan Jayadeva
May 10 · 6 min read

Hello Guys, I’m Senura Vihan Jayadeva. Today I’m going to show you how to send SMS with Twilio using Spring Boot.

What is Twilio?

Twilio is an American cloud communications platform as a service company based in San Francisco, California. Twilio allows software developers to programmatically make and receive phone calls, send and receive text messages, and perform other communication functions using its web service APIs.

Step 1

First of all, you have to create a Twilio account. For testing purposes, you can use a free account. But there you will be only able to send SMS for a specific phone number which you have given.

Go to https://www.twilio.com and click on the Sign up button. Then you will navigate to a page like this.

After submitting your details you will receive a verification email.

Then click on the Confirm Your Email link. Then you will navigate to a page like below. Here we have to provide a valid mobile number. Actually, for the free account, SMS will be sent only to this given number.

Then click on the Verify button. Then you have to fill the following fields as your requirement.

Then we will navigate the Twilio dashboard.

To use SMS, you will need a phone number from Twilio. On your trial account, you can get one free USA or Canada phone number. Now let’s click on the Get a trial phone number button.

Then you will able to see a popup box like below. Here you are getting a phone number. Then click on the Choose this Number.

If everything okay. In the dashboard, we will able to see Account SID, Auth Token, and Phone Number under the Project Info. We will keep these details for future use.

Step 2

Next, we have to initialize a spring boot application. If you don’t have an idea about spring boot follow the link below.

Make sure to add spring web, spring validation, and Twilio dependencies.

<dependency> 
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>7.34.0</version>
</dependency>

After adding those specific dependencies your pom.xml file should be like below.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.twilio</groupId>
<artifactId>springsms</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springsms</name>
<description>Demo project for send sms using Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>7.34.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

Step 3

Next, create a class called TwilioConfiguration inside the com.twilio.demo package. Then implement the following code.

package com.twilio.demo;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties("twilio")
public class TwilioConfiguration {
private String accountSid;
private String authToken;
private String trialNumber;
public TwilioConfiguration() { } public String getAccountSid() {
return accountSid;
}
public void setAccountSid(String accountSid) {
this.accountSid = accountSid;
}
public String getAuthToken() {
return authToken;
}
public void setAuthToken(String authToken) {
this.authToken = authToken;
}
public String getTrialNumber() {
return trialNumber;
}
public void setTrialNumber(String trialNumber) {
this.trialNumber = trialNumber;
}
}

Then create another class called TwilioInitializer. Then implement the code below.

package com.twilio.demo;import com.twilio.Twilio;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TwilioInitializer {
private final static Logger LOGGER = LoggerFactory.getLogger(TwilioInitializer.class); private final TwilioConfiguration twilioConfiguration; @Autowired
public TwilioInitializer(TwilioConfiguration twilioConfiguration) {
this.twilioConfiguration = twilioConfiguration;
Twilio.init(
twilioConfiguration.getAccountSid(),
twilioConfiguration.getAuthToken()
);
LOGGER.info("Twilio initialized ... with account sid {} ", twilioConfiguration.getAccountSid());
}
}

The next thing we have to do is create a modal for Sms. For that, you have to class called SmsRequest.

package com.twilio.demo;import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.constraints.NotBlank;
public class SmsRequest { @NotBlank
private final String phoneNumber; // destination
@NotBlank
private final String message;
public SmsRequest(@JsonProperty("phoneNumber") String phoneNumber,
@JsonProperty("message") String message) {
this.phoneNumber = phoneNumber;
this.message = message;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getMessage() {
return message;
}
@Override
public String toString() {
return "SmsRequest{" +
"phoneNumber= ..." + '\'' +
", message='" + message + '\'' +
'}';
}
}

After implementing the SmsRequest class then we have to create an interface for define a method to send SMS. There we are going to pass SmsRequest class as a parameter.

package com.twilio.demo;public interface SmsSender {    void sendSms(SmsRequest smsRequest);    // or maybe void sendSms(String phoneNumber, String message);
}

Then inside the same package create a class called TwilioSmsSender. Then implement the following code.

package com.twilio.demo;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.rest.api.v2010.account.MessageCreator;
import com.twilio.type.PhoneNumber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("twilio")
public class TwilioSmsSender implements SmsSender {
private static final Logger LOGGER = LoggerFactory.getLogger(TwilioSmsSender.class); private final TwilioConfiguration twilioConfiguration; @Autowired
public TwilioSmsSender(TwilioConfiguration twilioConfiguration) {
this.twilioConfiguration = twilioConfiguration;
}
@Override
public void sendSms(SmsRequest smsRequest) {
if (isPhoneNumberValid(smsRequest.getPhoneNumber())) {
PhoneNumber to = new PhoneNumber(smsRequest.getPhoneNumber());
PhoneNumber from = new PhoneNumber(twilioConfiguration.getTrialNumber());
String message = smsRequest.getMessage();
MessageCreator creator = Message.creator(to, from, message);
creator.create();
LOGGER.info("Send sms {}", smsRequest);
} else {
throw new IllegalArgumentException(
"Phone number [" + smsRequest.getPhoneNumber() + "] is not a valid number"
);
}
} private boolean isPhoneNumberValid(String phoneNumber) {
// TODO: Implement phone number validator
return true;
}
}

Next what we have to do is create a service class called SmsService. Inside the SmsService we are going to implement the logic to send SMS.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
@org.springframework.stereotype.Service
public class SmsService {
private final SmsSender smsSender;
@Autowired
public SmsService(@Qualifier("twilio") TwilioSmsSender smsSender) {
this.smsSender = smsSender;
}
public void sendSms(SmsRequest smsRequest) {
smsSender.sendSms(smsRequest);
}
}

Finally, we have to implement the controller class for processing incoming REST API requests. Create a class called SmsController and add the below code.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;@RestController
@CrossOrigin("*")
@RequestMapping("/api/v1/sms")
public class SmsController {
private final SmsService smsService; @Autowired
public SmsController(SmsService smsService) {
this.smsService = smsService;
}
@PostMapping
public void sendSms(@Valid @RequestBody SmsRequest smsRequest) {
smsService.sendSms(smsRequest);
}
}

Step 4

Right, Now we are going to configure the application.properties file and there you have to provide the Account SID, Auth Token, and Phone Number.

You can get the above details from the Twilio dashboard.

Step 5

Now as the final step we should test the APIs using software like Postman.

Before tests, the APIs make sure to run the Spring Boot application first.

Github Link: https://github.com/senuravihanjayadeva/spring-sms-demo

This is the end of this tutorial. Hope you learned something. Thank you !.