You are currently viewing Sending SMS Messages with Twilio and Spring Boot

Sending SMS Messages with Twilio and Spring Boot

In this tutorial, we will explore how to leverage Twilio’s APIs within a Spring Boot application to send SMS messages. Spring Boot, known for its simplicity and convention-over-configuration approach, is a popular choice for building robust Java applications, making it an excellent framework for integrating with Twilio.

Prerequisites

  • Java installed on your machine (version 8 or higher)
  • Spring Boot installed
  • Twilio account (sign up at https://www.twilio.com/)

Step 1: Create a Spring Boot Application

If you haven’t already set up a Spring Boot project, you can do so using Spring Initializr (https://start.spring.io/) or your preferred method.

Step 2: Add Twilio Dependency

Add the Twilio dependency to your pom.xml if you are using Maven:

<dependency>
    <groupId>com.twilio.sdk</groupId>
    <artifactId>twilio</artifactId>
    <version>8.23.0</version> <!-- Check for the latest version -->
</dependency>

Or if you are using Gradle, add to your build.gradle:

implementation 'com.twilio.sdk:twilio:8.23.0' // Check for the latest version

Step 3: Configure Twilio

You’ll need your Twilio Account SID and Auth Token to authenticate. These can be found on your Twilio dashboard after logging in.

Create a TwilioConfig class to hold your Twilio credentials:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.twilio.Twilio;

@Configuration
public class TwilioConfig {

    @Value("${twilio.accountSid}")
    private String accountSid;

    @Value("${twilio.authToken}")
    private String authToken;

    @Bean
    public void twilioInit() {
        Twilio.init(accountSid, authToken);
    }
}

Make sure to include these properties in your application.properties or application.yml:

twilio.accountSid=YOUR_ACCOUNT_SID
twilio.authToken=YOUR_AUTH_TOKEN

Step 4: Create SMS Service

Create a service to handle sending SMS messages. Let’s call it SmsService.

import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class SmsService {

    @Value("${twilio.phoneNumber}")
    private String twilioPhoneNumber;

    public void sendSms(String to, String messageBody) {
        try {
            Message message = Message.creator(
                    new PhoneNumber(to),
                    new PhoneNumber(twilioPhoneNumber),
                    messageBody
            ).create();
            System.out.println("Message sent successfully: " + message.getSid());
        } catch (Exception e) {
            System.err.println("Error sending SMS: " + e.getMessage());
        }
    }
}

Make sure to include your Twilio phone number in the application.properties:

twilio.phoneNumber=YOUR_TWILIO_PHONE_NUMBER

Step 5: Create a Controller

Create a controller to expose an API endpoint for sending SMS messages.

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.RestController;

@RestController
public class SmsController {

    private final SmsService smsService;

    @Autowired
    public SmsController(SmsService smsService) {
        this.smsService = smsService;
    }

    @PostMapping("/send-sms")
    public String sendSms(@RequestBody SmsRequest smsRequest) {
        smsService.sendSms(smsRequest.getTo(), smsRequest.getMessage());
        return "SMS sent successfully";
    }
}

Step 6: Create a Request Object

Create a simple request object to receive the SMS details.

public class SmsRequest {

    private String to;
    private String message;

    // Getters and Setters
}

Step 7: Run Your Application

Now you can run your Spring Boot application. Ensure it starts up without errors.

Step 8: Test the Endpoint

Using a tool like Postman or cURL, send a POST request to http://localhost:8080/send-sms with a JSON body like this:

{
    "to": "+1234567890",
    "message": "Hello from Twilio and Spring Boot!"
}

Replace +1234567890 with the phone number you want to send the SMS to. You should receive a response indicating success, and the SMS should be sent to the provided number.

Conclusion

You’ve now created a Spring Boot application that can send SMS messages using Twilio. This is a basic example, and in a real-world application, you would want to add error handling, validation, and possibly store/send more complex message formats. But this should give you a good starting point!

Leave a Reply