eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

eBook – Guide Spring Cloud – NPI (cat=Cloud/Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

1. Introduction

Sending SMS messages is a big part of many modern applications. There are a variety of uses cases that SMS messages can serve: two-factor authentication, real-time alerts, chatbots, and many more.

In this tutorial, we’ll build a simple Java application that sends SMS messages using Twilio.

There are a number of services that provide SMS capabilities, such as Vonage, Plivo, Amazon Simple Notification Service (SNS), Zapier, and more.

Using the Twilio Java client, we can send an SMS message in just a few lines of code.

2. Setting up Twilio

To get started we’ll need a Twilio account. They offer a trial account that is sufficient for testing every feature of their platform.

As part of the account setup, we must also create a phone number. This is important because the trial account requires a verified phone number for sending messages.

Twilio offers a quick setup tutorial for new accounts. Once we complete the account setup and verify our phone number, we can start sending messages.

3. Introduction to TwiML

Before we write our sample application, let’s take a quick look at the data exchange format used for Twilio services.

TwiML is a proprietary markup language based on XML. The elements in a TwiML message mirror the different actions we can take related to telephony: make a phone call, record a message, send a message, and so on.

Here is an example TwiML message for sending an SMS:

<Response>
    <Message>
        <Body>Sample Twilio SMS</Body>
    </Message>
</Response>

And here is another example TwiML message that makes a phone call:

<Response>
    <Dial>
        <Number>415-123-4567</Number>
    </Dial>
</Response>

These are both trivial examples, but they give us a good understanding of how TwiML looks like.  It’s composed of verbs and nouns that are easy to remember and directly relate to the action we’d perform with a phone.

4. Sending SMS in Java with Twilio

Twilio provides a rich Java client that makes interacting with their services easy. Instead of having to write code that builds TwiML messages from scratch, we can use an out-of-the-box Java client.

4.1. Dependencies

We can download the dependency directly from Maven Central or by adding the following entry to our pom.xml file:

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

4.2. Sending an SMS

To get started, let’s look at some sample code:

Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
Message message = Message.creator(
    new PhoneNumber("+12225559999"),
    new PhoneNumber(TWILIO_NUMBER),
    "Sample Twilio SMS using Java")
.create();

Let’s break down into key pieces the code in the above sample:

  • The Twilio.init() call is required once to set up the Twilio environment with our unique Account Sid and Token
  • The Message object is the Java equivalent to the TwiML <Message> element we saw earlier
  • Message.creator() requires 3 parameters: To phone number, From phone number, and the message body
  • The create() method handles sending the message

4.3. Sending an MMS

The Twilio API also supports sending multimedia messages. We can mix and match text and images, for this to work the receiving phone must support media messaging:

Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
Message message = Message.creator(
    new PhoneNumber("+12225559999"),
    new PhoneNumber(TWILIO_NUMBER),
    "Sample Twilio MMS using Java")
.setMediaUrl(
    Promoter.listOfOne(URI.create("http://www.domain.com/image.png")))
.create();

5. Tracking Message Status

In the previous examples, we didn’t confirm if the message was actually delivered. However Twilio provides a mechanism for us to determine whether a message was successfully delivered or not.

5.1. Message Status Codes

When sending a message, it’ll have one of the statuses at any time:

  • Queued – Twilio has received the message and queued it for delivery
  • Sending – the server is in the process of dispatching your message to the nearest upstream carrier in the network
  • Sent – the message was successfully accepted by the nearest upstream carrier
  • Delivered – Twilio has received confirmation of message delivery from the upstream carrier, and possibly the destination handset when available
  • Failed – the message couldn’t be send
  • Undelivered – the server has received a delivery receipt indicating the message wasn’t delivered

Note that for the last two statuses we can find an error code with more specific details to help us troubleshoot delivery problems.

The Twilio Java Client offers a synchronous and asynchronous methods to fetch status. Let’s have a look.

5.2. Checking Delivery Status (Synchronous)

Once we’ve created a Message object, we can call Message.getStatus() to see which status it’s currently in:

Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
ResourceSet messages = Message.reader().read();
for (Message message : messages) {
    System.out.println(message.getSid() + " : " + message.getStatus());
}

Note that Message.reader().read() makes a remote API call so use it sparingly. By default, it returns all messages we’ve sent, but we can filter the returned messages by phone numbers or date range.

5.3. Checking Delivery Status (Async)

Because retrieving message status requires a remote API call, it can take a long time. To avoid blocking the current thread, the Twilio Java client provides also an asynchronous version of Message.getStatus().read().

Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
ListenableFuture<ResourceSet<Message>> future = Message.reader().readAsync();
Futures.addCallback(
    future,
    new FutureCallback<ResourceSet<Message>>() {
        public void onSuccess(ResourceSet<Message> messages) {
            for (Message message : messages) {
                System.out.println(message.getSid() + " : " + message.getStatus());
             }
         }
         public void onFailure(Throwable t) {
             System.out.println("Failed to get message status: " + t.getMessage());
         }
     });

This uses the Guava ListenableFuture interface to process the response from Twilio on a different thread.

6. Conclusion

In this article, we learned how to send SMS and MMS using Twilio and Java.

While TwiML is the basis of all messages to and from Twilio servers, the Twilio Java client makes sending messages incredibly easy.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
eBook – eBook Guide Spring Cloud – NPI (cat=Cloud/Spring Cloud)