Send SMS with Twilio using Spring Boot

What is Twilio?

Step 1

Step 2

<dependency> 
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>7.34.0</version>
</dependency>
<?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

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;
}
}
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());
}
}
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 + '\'' +
'}';
}
}
package com.twilio.demo;public interface SmsSender {    void sendSms(SmsRequest smsRequest);    // or maybe void sendSms(String phoneNumber, String message);
}
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;
}
}
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);
}
}
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

Step 5

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Senura Vihan Jayadeva

Senura Vihan Jayadeva

93 Followers

Software Engineering undergraduate of Sri Lanka Institute of Information Technology | Physical Science Undergraduate of University of Sri Jayewardenepura