Twilio Java API, Twilio Send SMS with Spring Boot

Home / Twilio Java API, Twilio Send SMS with Spring Boot

In this example, we will learn about how to send SMS to mobile numbers using spring boot and Twilio ( Twilio Java API). So we have to see first that what is Twilio?

Twilio is an American-based cloud communication company that provides many services like Calling, SMS, and IVR. Twilio provides you a free trial of up to 15$. We can use this 15$ to test our application feature for calling or sending SMS.

As we are going to send Text SMS to mobile numbers in this example ( Twilio Java API ). So we have to create a Twilio account. After SignUp to Twilio, we get Account SID and Auth Token. We use these two values in our Spring boot application to send SMS. We can also set up one test number provided by Twilio to Send SMS.

So we will complete this application in Two Steps:

  1. Create the Twilio Account.
  2. Integrate Twilio in our Spring boot application.

Step 1 : Create Twilio Account

You have to follow the below steps to sign up on Twilio.

  1. Open Twilio Website using URL ( https://www.twilio.com/ )
  2. Click on the Sign-up button.
  3. Fill in your details and click on Start your free trial.
  4. After that, you will get a verification link on your email just verify that link.
  5. Now You have to enter your mobile number to verify. After entering the number, you will get an OTP just submit that OTP.
  6. You have to fill in the basic details now means what service you want to use. What will you build with Twilio etc?
  7. Congrats your Twillio Account is set up now.
  8. Now you have to set up a Test number using which you send the SMS. So for that, you have to click on get a trial phone number.

Twilio
Twilio Java API
java Twilio
Twilio java

Now see your dashboard you have all three details that you needed. account SID, accountAuthToken, and a Trial number.

Step 2: Create Spring Boot Application And Integrate Twilio.

1- To Integrate Twilio with Spring boot we use the Twilio SDK. So You can use the below maven dependency for Twilio SDK.

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

2- Now we follow the simple MVC architecture. We create a Controller class that has a POST method.

This POST Method accepts two parameters that is SMS Text and the mobile number to whom we have to send the SMS.

To accept these parameters we create a POJO class.

Now we create the service class to write the business logic.

In this service class, we initialize the Twilio using account SID and auth Token.

We use the few classes of Twilio one is PhoneNumber, this class is used to convert our string mobile number into a phone number.

Second class is MessageCreator it accepts three parameters:

  1. Receiver Phone Number
  2. Sender Phone Number
  3. SMS text message

Now we have to send the Text Message. So for this MessageCreator class has a method create(). So This method returns the Message class which has some final methods like getPrice(), getStatus().

So we create a controller class now.

package com.javadream.controller;

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

import com.javadream.model.MessageModel;
import com.javadream.service.TwilloMessageSenderService;

@RestController
@RequestMapping("/twillo")
public class TwilloController {

	
	@Autowired
	private TwilloMessageSenderService twilloService;
	
	@PostMapping("/sendSMS")
	public String sendSMSByTwillo(@RequestBody MessageModel messageRequest) {
		String sendMessageResponse = twilloService.sendMessage(messageRequest);
		return sendMessageResponse;
	}
}

This is a controller class that has one Post method. So our POST endpoint will be:

http://localhost:8080/twillo/sendSMS

This class accepts a Pojo class as a parameter in the POST method. So we create this Pojo class. And after that, we Autowired our service class. So we also have to create this service class where we write our business logic.

MessageModel.Java

package com.javadream.model;

public class MessageModel {

	private String mobileNumber;
	private String smsText;

	public MessageModel() {
		super();
	}

	public MessageModel(String mobileNumber, String smsText) {
		super();
		this.mobileNumber = mobileNumber;
		this.smsText = smsText;
	}

	public String getMobileNumber() {
		return mobileNumber;
	}

	public void setMobileNumber(String mobileNumber) {
		this.mobileNumber = mobileNumber;
	}

	public String getSmsText() {
		return smsText;
	}

	public void setSmsText(String smsText) {
		this.smsText = smsText;
	}

}

Now we have to create the Service class.

TwilloMessageSenderService.java

package com.javadream.service;

import java.math.BigDecimal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.javadream.model.MessageModel;
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.rest.api.v2010.account.Message.Status;
import com.twilio.rest.api.v2010.account.MessageCreator;
import com.twilio.type.PhoneNumber;

@Service
public class TwilloMessageSenderService {

	private static final Logger logger = LoggerFactory.getLogger(TwilloMessageSenderService.class);

	@Value("${accountSID}")
	private String accountSID;

	@Value("${accountAuthToken}")
	private String accountAuthToken;

	@Value("${twilloSenderNumber}")
	private String twilloSenderNumber;

	public String sendMessage(MessageModel messageRequest) {
		try {
			Twilio.init(accountSID, accountAuthToken);

			String smsText = messageRequest.getSmsText();
			String mobileNumber = messageRequest.getMobileNumber();

			PhoneNumber recieverPhoneNumber = new PhoneNumber(mobileNumber);
			PhoneNumber senderTwilloPhoneNumber = new PhoneNumber(twilloSenderNumber);

			MessageCreator creator = com.twilio.rest.api.v2010.account.Message.creator(recieverPhoneNumber, senderTwilloPhoneNumber, smsText);
			Message create = creator.create();
			
			BigDecimal billingAmount = create.getPrice();
			Status status = create.getStatus();
			
			
			logger.info("Message Send Succesfully to the number " + mobileNumber);
			return "Message Send Succesfully";
		} catch (Exception e) {
			logger.error("Exception in sendMessage Method " + e);
			return "Message Send Fail";
		}

	}

}

Twilio with Spring boot

As you can see we are reding accountSID, accountAuthToken, twilloSenderNumber from the application.properties file. So make this entry in your application. properties file.

application.properties

accountSID=Copy From Twilio Dashboard
accountAuthToken=Copy From Twilio Dashboard
twilloSenderNumber=+1772252

Now Run Your application and hit your POST end point from Postman.

Twilio Spring boot

Note: Make Sure you use +Your Country code before your number in our case we are using an Indian number so we are using +91.

Now check your mobile You will recieve a SMS from Twilio Number.

Twilio Java Api

Get Complete Code On GitHub: Twilio With Spring Boot

Like Our Facebook Page

You may also like:

Why you should avoid Split() methos and use alternate of this splitAsStream() method in java.

Spring Batch Complete tutorial Execute big task in small small chunks

Avoid NullPointerException using java8 optional complate Example

Help Others, Please Share

About Author

Leave a Reply

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

x