Sending sms using twilio and Java | Spring Boot

Badri Paudel
6 min readMar 18, 2022

Sending sms is pretty common in modern applications and it can be complex. However, with spring boot and twilio, it’s just a piece of a cake. We can see our app being capable of sending sms in just few minutes and you can leverage to any level you want.

Photo by Sara Kurfeß on Unsplash

Sending SMS nowadays in most of the applications is pretty common thing to confirm identity like sending secret codes, two factor authentication, order messages from different shopping sites and so on. Twilio is one of the such sms providers with large market share and many companies are using it as it is probably one of the easy to implement services in most of the programming languages and even beyond that. In this article I will show you how to send sms using twilio service in Java application. For this purpose I will be using Spring boot along with java to make it even realistic and practical.

As we’re going to use some third party library and our main focus is how to use that, this tutorial expects that you have basic understanding of Java and fundamental understanding of spring or spring boot.

To send sms using twilio, we need to set up account first, first of all go to twilio website and fill up the basic information required to get the credentials. Make sure that you get following Information from the twilo after you’ve signed up.

If you’ve successfully got those credentials, now it’s time to create a fairly simple spring boot application either in IDE directly or from the this official website’s link. I will be using IntelliJ IDEA to complete this tutorial, just select the web dependency and that’s all for now ,we will add twilio dependency in just a few seconds, choose maven as build tool as I will be using maven as dependency management, you’re free to choose gradle if you’re comfortable with it. After creating project just open the project in your IDE and will look very similar to this :

Let’s pretend that we’re working on a big project and trying to organize the project in better and maintainable way which is really a good learning practice as well. In spring boot application , I will create some folders [packages to organize the codes] to put some particular code. config folder will hold the file related to twilio configuration, resources will hold the code for our fairly simple rest API, and services for our business logic related file. The screenshot shows what exactly you need to create

It is now time to add twilo credentials that we’ve already created in the file so that we can achieve the message sending capability. In spring boot, special file called application.properties hold this [ we can use application.yml file as well]. So open application.properties file and paste the followoing code.

#application.properties file 
#properties for twilio
twilio.account_sid=useyours
twilio.auth_token=useyours
twilio.trial_number=useyours

Now let’s add twilio dependency and add it to our pom.xml file so that we can use methods available to send sms. Go to maven central repository , grab it and add the following dependency in the pom.xml file inside of the dependencies tag as follows

<!-- dependency for twilio sms --> 
<!-- https://mvnrepository.com/artifact/com.twilio.sdk/twilio --> <dependencies>
.... other dependencies
<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>7.50.1</version>
</dependency>
</dependencies>

Let’s configure twilo in TwilioConfig.java file inside of the config package. Add the following code

import org.springframework.beans.factory.annotation.Value; 
import org.springframework.context.annotation.Configuration;
@Configuration
public class TwilioConfig {
//twilio gives us account_sid , auth_token and trial number
@Value(“${twilio.account_sid}”)
private String accountSid;
@Value(“${twilio.auth_token}”)
private String authToken;
@Value(“${twilio.trial_number}”)
private String trialNumber;
public TwilioConfig() {
// default constructor
}
public String getAccountSid() {
return accountSid;
}
public String getAuthToken() {
return authToken;
}
public String getTrialNumber() {
return trialNumber;
}
}

In above file @Configuration annotation tells the app that this bean available on app loading and @Value annotation with name inside of small bracket are coming from application.properties file which we've just created.

Let’s create another file called TwilioInitailizer.java that actually initializes twilio itself using above file. Inside of the config package, add TwilioInitailizer.java file and paste the following code.

// content of TwilioInitailizer.java file
import org.slf4j.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import com.twilio.Twilio;
@Configuration
public class TwilioInitializer {
private static final Logger logger = org.slf4j.LoggerFactory.getLogger(TwilioInitializer.class);
private TwilioConfig twilioConfig;
@Autowired
public TwilioInitializer(TwilioConfig twilioConfig) {
this.twilioConfig = twilioConfig;
Twilio.init( twilioConfig.getAccountSid(), t wilioConfig.getAuthToken() ); logger.info("twilio Initialized with ..... " + twilioConfig.getAccountSid()); }
}

Above file is important, first of all this injects TwilioConfig file which has set up the configuration for the twilo and calls init method available for us in Twilio itself by passing required parameters.

Let’s create a small endpoint /sms, which when hit on the browser actually send the sms with ‘hello from twilio’ message. For this inside of the resources package, create a file called TwilioResource.java file and add following code.

import org.springframework.web.bind.annotation.GetMapping; 
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TwilioResources {
// Inject the TwilioSMS service
@GetMapping("/sms") public void sendSMS() {
// send the message
}
}

The above file tells that when http://localhost:8080/sms will do some work, here probably send the sms to the number. But let’s separate our file so that when called TwilioService.java will handle the job of sending sms. Let's do that.

Inside of the services package, create a file called TwilioService.java and write the following code.

import com.example.twiliosmsjava.config.TwilioConfig; 
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
public class TwilioService {
private static final Logger logger = LoggerFactory.getLogger(TwilioService.class);
@Autowired
TwilioConfig twilioConfig;
public boolean sendSMS() {
MessageCreator creator = new MessageCreator( new PhoneNumber("your verified number from twilio with country code"),
new PhoneNumber(twilioConfig.getTrialNumber()),
"Hello From Twilio" );
try {
creator.create();
return true;
}
catch (Exception e) {
logger.error("Something went wrong");
return false;
}
}
}

It is time to use above service in our resources , first of all let’s inject that file in our TwilioResources.java file and call the method on it. Finally our file will look like this :

@RestController public class TwilioResources { 
// Inject the TwilioSMS service
@Autowired TwilioService twilioService;
@GetMapping("/sms")
public String sendSMS() {
// send the message boolean isSent = twilioService.sendSMS();
if(isSent) {
return "SMS Sent Successfully to the provided number";
}
return "SMS Couldn't be sent";
}
}

Make sure that you’ve verified your number with twilio as free trial can’t be performed on other numbers. Now let’s run our app and see if it works. To confirm , run the app and hit the browser http://localhost:8080/sms and you’ll see message in the browser and message in your phone number. Let’s confirm that :

By now you should have gotten the sms with some messages in your verified phone number and that’s amazing , you’ve done it. Cheers ! and happy coding. If you’re looking for the source code, I have a complete code in the repository which you can use, just make sure to add required credentials in application.properties file.

One more Note : In this small application, we sent sms directly when url is requested, but in real projects we’re not supposed to do this way. How do we handle sms in real time project is little different, probably we will maintain a separate sms table which will have properties like from, to, message to send and status and more. Our regular job will eventually fetch sms periodically and sent as mentioned in saved sms and update status to sent or very much similar.

Originally published at https://guidestocode.com on March 18, 2022.

--

--

Badri Paudel

Software Engineer, exploring different languages & frameworks. Working with Java/Groovy, Spring/Grails, Javascript, Postgres & more. Love Sharing what I know.