Skip to Content

How to send SMS using Twilio in java?

Sending SMS messages programmatically is a common need for many applications. Whether you want to send notifications, alerts, OTP codes or reminders via SMS, the ability to send SMS from your backend server can be very useful.

In this tutorial, we’ll see how to send SMS using Twilio’s Java API. Twilio is a popular cloud communications platform that makes it easy to send SMS, make voice calls and more from your apps and services.

What is Twilio?

Twilio is a cloud communications platform as a service (CPaaS) provider. It allows developers to programmatically make and receive phone calls, send and receive text messages, and perform other communication functions using its web service APIs.

Some key capabilities offered by Twilio include:

  • SMS: Send and receive SMS messages
  • Voice: Make and receive phone calls
  • Video: Add video calling capabilities to your app
  • Chat: Build chat messaging into your app
  • Two-factor authentication via SMS

Twilio is designed as a backend service to power the communication needs of web and mobile applications. Many well known companies like Airbnb, Uber, Mailchimp and others use Twilio for their communication features.

Why use Twilio for sending SMS?

Here are some of the key benefits of using Twilio for sending SMS messages:

  • Easy APIs – Simple REST APIs make sending SMS trivial
  • Scalable infrastructure – Built to send millions of messages
  • Flexible notifications – Send one to many messages or two way conversations
  • Global reach – SMS is available globally
  • Delivery receipts – Get notified when a message is delivered
  • Webhooks support – Trigger actions on incoming messages

In short, Twilio makes adding SMS capabilities to your application quick, scalable and flexible.

Prerequisites

Before we dive into the code, you’ll need to have the following:

  • A Twilio account – Sign up for a free trial account at Twilio
  • A Twilio phone number – Purchase a number in your Twilio console
  • The Twilio Java SDK – Add the Maven dependency as shown below
  • Java 8+

Twilio Account and Phone Number

First, sign up for a free Twilio account. This allows you to access the Twilio console where you can purchase phone numbers, view your API credentials and monitor your account.

Next, purchase a Twilio phone number in your console. This will be the “from” number when sending SMS messages. Make sure to choose a number that supports SMS messaging.

Once you have the number, you’ll need to note down the Account SID and Auth Token from the console. These credentials are used to authenticate your Java app when accessing the Twilio API.

Twilio Java SDK

Twilio provides an official Java SDK to simplify working with their APIs. You can add it to your project using Maven:

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

This will add the Twilio jars to your classpath. Now we are ready to write some code!

Sending an SMS with Twilio

Let’s jump right into an example of sending SMS with Twilio in Java. We’ll need a few prerequisites:

  • Import the Twilio Java SDK classes
  • Initialize the Twilio client with your Account SID and Auth Token
  • Use the Message creator to build a new SMS message
  • Set the “from” number using your Twilio number
  • Add a “to” number to send the message to
  • Send the message and check for errors

Here is the code:

import com.twilio.Twilio; 
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;

public class SendSms {

  // Find your Account SID and Auth Token at twilio.com/console
  public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  public static final String AUTH_TOKEN = "your_auth_token";

  public static void main(String[] args) {
    Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

    Message message = Message.creator(new PhoneNumber("+1234567890"), 
            new PhoneNumber("+1234567891"), 
            "Hello from Java!").create();

    System.out.println(message.getSid());
  }
}  

Let’s understand what’s happening here:

  1. We import classes from the Twilio SDK
  2. Initialize the Twilio client with our Account SID and Auth Token
  3. Construct a Message object using the creator
  4. Set the “from” number to our Twilio number
  5. Add the “to” number we want to send to
  6. Add the text body of the message
  7. Call create() which sends the API request to Twilio
  8. Print the message SID on success

And that’s it! With just a few lines of code, we have programmatically sent an SMS using the Twilio API.

Send SMS with Custom Parameters

The basic SMS example sends a simple text message. But Twilio supports many options and parameters to control your message delivery.

Here are some common examples:

Send an MMS with Media

To send a multimedia message (MMS) containing images, videos or documents, you can add media URLs to the message:

// MMS example 
Message message = Message.creator(new PhoneNumber("+1234567890"), 
      new PhoneNumber("+1234567891"),  
      "MMS Message!").setMediaUrl(Collections.singletonList("https://demo.twilio.com/logo.png")).create();

Schedule a Message

You can schedule a message to be sent at a specific date/time:

// Schedule example
LocalDateTime scheduled = LocalDateTime.now().plusMinutes(1); 
Message message = Message.creator(new PhoneNumber("+1234567890"),
       new PhoneNumber("+1234567891"),
       "Hello at " + scheduled).setSendAt(scheduled).create();

Reply Back to a Number

To enable two-way messaging, set your Twilio number as the “from” address and specify the reply number:

// Reply example
Message message = Message.creator(new PhoneNumber("+15551234567"), // Your Twilio number
       new PhoneNumber("+1234567891"),  
       "Reply back to me!").setProvideFeedback(true)
     .setFeedbackCallback(new PhoneNumber("+12345678912"))
     .create();

This allows the message receiver to reply directly back to your program.

Receive Message Status Updates

You can get delivery receipts and status notifications by passing in a URL webhook:

// Status example
Message message = Message.creator(new PhoneNumber("+1234567890"),  
       new PhoneNumber("+1234567891"),
       "SMS notification example").setStatusCallback(new URI("https://mydomain.com/sms_callback"))
       .create();

There are many other options available as well – you can see the full Message documentation here.

Receive Inbound SMS

So far we’ve looked at sending outbound messages. Twilio also makes it easy to receive incoming SMS messages to your Twilio number.

To handle incoming messages, you configure a webhook URL on your phone number. We’ll deploy a simple servlet to print messages to the console.

First, configure your Twilio number to call your webhook URL in the console:

Now when your Twilio number receives a message, it will make an HTTP request to this URL.

Here is sample code for a servlet that handles this request:

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

public class IncomingSms extends HttpServlet {

  public void service(HttpServletRequest req) {
    String from = req.getParameter("From");
    String body = req.getParameter("Body");

    System.out.println("New SMS from " + from);
    System.out.println(body);
  }

}  

This basic servlet just prints out the “From” number and message body. In your real app, you could instead:

  • Save the messages to a database
  • Send an automated reply
  • Forward to an email or phone
  • Trigger any application logic

So with just a few lines of code, you have a way to receive SMS messages sent to your Twilio number and process them any way you need!

Send SMS with Client

The examples so far use the Twilio REST APIs directly. Another option is to use the Twilio Java SDK Client.

This provides an abstraction layer and handles some lower level details for you automatically. Here is an example:

// Import the Twilio SDK packages  
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;

public class SendSmsClient {

  public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; 
  public static final String AUTH_TOKEN = "your_auth_token";

  public static void main(String[] args) {
    // Initialize the client
    Twilio.init(ACCOUNT_SID, AUTH_TOKEN); 

    // Send message using client
    Message message = Message.creator(
            new PhoneNumber("TWILIO_NUMBER"), 
            new PhoneNumber("TO_NUMBER"),  
            "Hello from the Twilio SDK!").create();

    System.out.println(message.getSid());
  } 
}

The client approach has some advantages:

  • Reusable client – initialize once, make many API calls
  • Request retry and exception handling
  • Convenience methods like getPage()

But the basic REST API is more flexible if you need low level control.

Best Practices

Here are some tips for using Twilio APIs in your applications:

  • Store credentials securely – Use environment variables or key stores
  • Validate phone numbers – Sanitize and verify formats
  • Handle errors gracefully – TwiML exceptions, invalid numbers etc
  • Use helper libraries – Like the official Java SDK
  • Monitor usage – Watch your account for anomalies
  • Follow Twilio guidelines – Stay compliant with SMS regulations

Following these best practices will ensure your application remains stable, secure and compliant when sending SMS at scale.

Sending SMS from Twilio Console

For testing purposes, you can also easily send one-off SMS messages directly from the Twilio console.

Just navigate to the SMS section and click the “Send an SMS” button:

This allows you to quickly test sending messages without writing any code. You can verify messages received on your own cell phone.

The console is great for experimenting, but for any production use case you’ll want to use proper API calls.

Twilio Use Cases

Here are some common use cases where sending SMS with Twilio can be very useful:

2 Factor Authentication

Many sites now use SMS for 2FA when logging in for better security. Twilio lets you implement this easily.

Notifications & Alerts

Send SMS alerts for new signups, offers and promotions. Or trigger SMS on events.

OTP Verification

Send one time passwords by SMS for account verification during signup.

Chatbots & Conversational SMS

Power more advanced conversational bots that users interact via SMS.

Appointment Reminders

Remind customers of upcoming appointments via SMS notifications.

Marketing & Promotions

Send marketing offers, coupons or promotions to a list of opted-in numbers.

The use cases are vast – pretty much anything that requires communicating via SMS can be built using the Twilio SMS APIs.

Conclusions

Sending SMS messages from your backend systems is made quick and painless using Twilio APIs.

As you’ve seen, the Twilio Java SDK provides simple methods to:

  • Send one-off SMS messages
  • Schedule messages for the future
  • Receive inbound messages
  • Reply to SMS conversations
  • Customize SMS delivery

Twilio handles all the telecom infrastructure, so you can focus on implementing SMS capabilities in your apps.

Some popular use cases include 2FA, notifications, alerts, marketing and conversational bots. But the possibilities are endless!

To get started, sign up for a free Twilio account and follow along with the examples. Add the Java SDK to your project, and you’ll be sending your first programmatic SMS messages in minutes!