Back to Blog
Integration Guides

How to Send SMS with Twilio and Spring Boot: Step-by-Step Tutorial

Add Twilio SMS to your Spring Boot application using the Twilio Java library with dependency injection, properties-based config, and async sending.

DA
Danial A
Senior Twilio Consultant, Telphi Consulting
June 22, 2026
7 min read
Twilio
Integration
SDK
Mobile
How to Send SMS with Twilio and Spring Boot: Step-by-Step Tutorial

Twilio SMS and Spring Boot integrate through the Twilio Java helper library added as a Maven or Gradle dependency, with credentials bound from application.properties or environment variables into a @ConfigurationProperties class, and SMS dispatch logic encapsulated in a Spring @Service bean that the DI container injects into controllers and scheduled jobs. This integration is used by Java development teams building Spring Boot microservices, REST APIs, or enterprise applications that need SMS for OTP verification, system alert notifications, appointment reminders, or transactional confirmations, and who want Twilio SMS dispatch to integrate naturally with Spring's dependency injection, @Async background execution, and Spring Boot Actuator health checks. The TwilioService bean initializes the Twilio client using @PostConstruct, dispatches messages via the Message.creator API, and can be called asynchronously from any Spring component using the @Async annotation.

What You Need Before You Start

Add the Twilio Java library to your Maven pom.xml by adding a dependency with groupId com.twilio.sdk, artifactId twilio, and the current version, then run mvn dependency:resolve. For Gradle, add implementation 'com.twilio.sdk:twilio:10.5.0' to build.gradle dependencies. Add Twilio credentials to application.properties with twilio.account-sid=${TWILIO_ACCOUNT_SID}, twilio.auth-token=${TWILIO_AUTH_TOKEN}, and twilio.from-number=${TWILIO_FROM_NUMBER}, using the ${VARIABLE} placeholder syntax so Spring Boot substitutes environment variable values at startup. Create a TwilioProperties.java class annotated with @ConfigurationProperties(prefix = 'twilio') and @Component with String fields accountSid, authToken, and fromNumber with getter and setter methods so Spring Boot auto-binds the properties. Collect your Twilio Account SID, Auth Token, and a provisioned SMS-capable phone number from the Twilio Console.

Step-by-Step Integration Guide

Create a TwilioService.java class annotated with @Service that injects TwilioProperties via constructor injection. Add a @PostConstruct method that calls Twilio.init(twilioProperties.getAccountSid(), twilioProperties.getAuthToken()) and throws an IllegalStateException with a descriptive message if either is null or empty. Define a sendSms(String to, String body) method that calls Message.creator(new PhoneNumber(to), new PhoneNumber(twilioProperties.getFromNumber()), body).create() wrapped in try/catch catching com.twilio.exception.ApiException, logs the exception using an injected Logger, and returns the message getSid() or throws a TwilioSmsException extending RuntimeException. Create a REST controller with @RestController and @RequestMapping('/api/sms') that injects TwilioService, exposes a @PostMapping endpoint that reads a request DTO with to and body fields from @RequestBody, calls twilioService.sendSms and returns a ResponseEntity with the SID and HTTP 200, or returns a 500 response with the error message caught from TwilioSmsException. Add @Async to a second sendSmsAsync method in TwilioService that returns CompletableFuture.completedFuture(sendSms(to, body)) for non-blocking callers.

Common Issues and How to Fix Them

The @PostConstruct method throws IllegalStateException at application startup when the TwilioProperties fields are null because the TWILIO_ACCOUNT_SID environment variable is not set in the environment where Spring Boot runs, and the application.properties placeholder ${TWILIO_ACCOUNT_SID} resolves to the literal string rather than throwing an error. Add @Validated to TwilioProperties and @NotBlank to each field so Spring Boot's configuration validation fails immediately at startup with a BindValidationException listing the missing properties rather than allowing the application to start and fail later. Calling the @Async sendSmsAsync method from within the same TwilioService class does not execute asynchronously because Spring's AOP proxy does not intercept self-calls within the same bean. Move @Async to a separate TwilioAsyncService bean that injects and calls the TwilioService, ensuring the @Async proxy wraps the cross-bean call correctly. The Message.creator call returns an ApiException with code 21614 when the destination number is a landline without SMS capability. Add a preliminary lookup using the Twilio Lookup API in a Spring service method that queries the line type before dispatching, skipping the message send and returning a structured error when the line type is not mobile.

How to Get More from This Integration

Integrate Spring Boot Actuator with a custom Twilio health indicator by implementing HealthIndicator, overriding health() to make a lightweight Twilio API call such as fetching account details with TwilioRestClient, returning Health.up() on success and Health.down() with an error detail map on failure, and registering the bean so it appears in the /actuator/health endpoint for monitoring dashboards. Build a Spring Batch job for bulk SMS sending by creating a step with an ItemReader that reads phone numbers and messages from a CSV file or database, an ItemProcessor that validates and normalizes each phone number using libphonenumber, and an ItemWriter that calls TwilioService.sendSms for each item with a configurable thread pool for parallelism, capping throughput to respect Twilio's rate limit for your account tier. Add Spring Retry to the TwilioService sendSms method by annotating it with @Retryable and adding a @Recover method that logs the final failure after all retries are exhausted, providing automatic retry with exponential backoff for transient Twilio API errors.

Conclusion

Spring Boot and Twilio together provide an enterprise-ready SMS integration using Spring's dependency injection, properties binding, and async execution to build a maintainable, testable notification service. Reach out to Telphi Consulting to design and implement the Twilio SMS service for your Spring Boot application.

Share this article:
0 views

Ready to Transform Your Business Communications?

Get a free consultation with our VoIP experts and discover how we can help you save costs, improve efficiency, and scale your business.

Comments (0)

Join the discussion and share your thoughts (AI-moderated for quality)

Protected by AI moderation

Be the first to comment

No comments yet. Share your thoughts below.