Skip to contentSkip to navigationSkip to topbar
On this page

Programmable Messaging Quickstart for Java


(information)

Info

Ahoy there! All messaging transmitted using Twilio's messaging channels is treated as Application-to-Person (A2P) messaging and subject to Twilio's Messaging Policy(link takes you to an external page). For detailed information on policy rules to ensure you remain compliant while using Twilio's services, please see our Acceptable Use Policy(link takes you to an external page).

Ready to start sending and receiving text messages with Twilio Programmable SMS using Java?

This Programmable SMS Quickstart for Java will teach you how to do this using the Twilio Java helper library for our Communications REST API.

In this Quickstart, you will learn how to:

  1. Sign up for Twilio and get your first SMS-enabled Twilio phone number
  2. Set up your development environment to send and receive messages
  3. Send your first SMS
  4. Receive inbound text messages
  5. Reply to incoming messages with an SMS

Prefer to get started by watching a video? Check out our Java SMS Quickstart video on YouTube(link takes you to an external page).


Sign up for - or sign in to - Twilio

sign-up-for---or-sign-in-to---twilio page anchor
(information)

Info

Already have a Twilio account? Go ahead and skip this section.

(warning)

Warning

If you are sending SMS to the U.S. or Canada, before proceeding further please be aware of updated restrictions on the use of Toll-Free numbers for messaging, including TF numbers obtained through Free Trial. Please click here(link takes you to an external page) for details.

You can sign up for a free Twilio trial account here(link takes you to an external page).

  • When you sign up, you'll be asked to verify your personal phone number. This helps Twilio verify your identity and also allows you to send test messages to your phone from your Twilio account while in trial mode.
  • Once you verify your number, you'll be asked a series of questions to customize your experience.
  • Once you finish the onboarding flow, you'll arrive at your project dashboard in the Twilio Console(link takes you to an external page) . This is where you'll be able to access your Account SID, authentication token, find a Twilio phone number, and more.

If you don't currently own a Twilio phone number with SMS functionality, you'll need to purchase one. After navigating to the Buy a Number(link takes you to an external page) page, check the SMS box and click Search.

Buy a twilio phone number.

You'll then see a list of available phone numbers and their capabilities. Find a number that suits your fancy and click Buy to add it to your account.

Select an SMS-enabled phone number.

We'll need to use the Twilio CLI (command line interface) for a few tasks, so let's install that next.

macOSWindowsLinux

The suggested way to install twilio-cli on macOS is to use Homebrew(link takes you to an external page). If you don't already have it installed, visit the Homebrew site(link takes you to an external page) for installation instructions and then return here.

Once you have installed Homebrew, run the following command to install twilio-cli:

brew tap twilio/brew && brew install twilio
(information)

Info

For other installation methods, see the Twilio CLI Quickstart.

Log in to the Twilio CLI

log-in-to-the-twilio-cli page anchor

Run twilio login to get the Twilio CLI connected to your account. Visit the Twilio Console(link takes you to an external page), and under Account Info, you'll find your unique Account SID and Auth Token to provide to the CLI.

Next, we need to install Java and the Twilio Java Helper Library.


Set up your Java environment

set-up-your-java-environment page anchor
(information)

Info

Already have your Java development environment all set up, and have a Twilio Java Helper library configured in your classpath? Feel free to skip the next two sections, and get right into sending your first text message with Twilio!

To send your first SMS, you'll need to have the Java Standard Edition (SE) Development Kit (JDK) installed - if you don't know if you have the JDK installed, run the following command to see what version you have:

javac -version

You should see something similar to this output:

javac 1.8.0_92

The Twilio SDK requires Java SE 8 or higher, which will appear as version number "1.8" or above when you run the above command.

If you have an older version of Java or no JDK at all, you'll need to install the JDK before going any further. Follow the directions for installing the Java SE Development Kit for your platform (Windows, Mac, Linux) from the Java SE Download Page(link takes you to an external page).


Download the standalone Twilio Java Helper Library

download-the-standalone-twilio-java-helper-library page anchor

Got Java all set up and ready to go? Fantastic!

Next, download the standalone Twilio Java Helper Library(link takes you to an external page). With that library, you'll have Java classes that help you call out to Twilio API's using Java, along with all the other dependencies you'll need to get going. We'll be using this "fat jar" file with all the dependencies in this SMS Quickstart. When you download the fat jar file, download the one with a name similar to twilio-8.x-jar-with-dependencies.jar.

Prefer to use Maven, Gradle, or another build tool? The Twilio Java Helper Library docs have information on how to install the helper library using a build automation tool(link takes you to an external page).

(warning)

Warning

This Twilio Java Helper Library is not meant for use in Android applications! Use this library for servers, command line applications, and similar projects.

If you want to send an SMS from a mobile application, you should have a server component with your Twilio credentials where your app sends an HTTP request. Shipping your Twilio Account SID and Auth Token to end users is a security risk for your Twilio account.


Send an outbound SMS message with Java

send-an-outbound-sms-message-with-java page anchor

Now that we have the JDK set up and the Twilio Java Helper Library downloaded, we can send an outbound text message from the Twilio phone number we just purchased with a single API request. Create and open a new file called Example.java and type or paste in this code sample. Move the Twilio Java Helper Library to be in the same directory as Example.java.

Send an SMS using Twilio with JavaLink to code sample: Send an SMS using Twilio with Java
1
// Install the Java helper library from twilio.com/docs/java/install
2
3
import com.twilio.type.PhoneNumber;
4
import com.twilio.Twilio;
5
import com.twilio.rest.api.v2010.account.Message;
6
7
public class Example {
8
// Find your Account SID and Auth Token at twilio.com/console
9
// and set the environment variables. See http://twil.io/secure
10
public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
11
public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");
12
13
public static void main(String[] args) {
14
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
15
Message message = Message.creator(
16
new com.twilio.type.PhoneNumber("+14159352345"),
17
new com.twilio.type.PhoneNumber("+14158141829"),
18
"Where's Wallace?")
19
.create();
20
21
System.out.println(message.getBody());
22
}
23
}

Output

1
{
2
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
3
"api_version": "2010-04-01",
4
"body": "Where's Wallace?",
5
"date_created": "Thu, 24 Aug 2023 05:01:45 +0000",
6
"date_sent": "Thu, 24 Aug 2023 05:01:45 +0000",
7
"date_updated": "Thu, 24 Aug 2023 05:01:45 +0000",
8
"direction": "outbound-api",
9
"error_code": null,
10
"error_message": null,
11
"from": "+14158141829",
12
"num_media": "0",
13
"num_segments": "1",
14
"price": null,
15
"price_unit": null,
16
"messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
17
"sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
18
"status": "queued",
19
"subresource_uris": {
20
"media": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json"
21
},
22
"tags": {
23
"campaign_name": "Spring Sale 2022",
24
"message_type": "cart_abandoned"
25
},
26
"to": "+14159352345",
27
"uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json"
28
}

You'll need to edit this file a little more before your message will send:

Replace the placeholder credential values

replace-the-placeholder-credential-values page anchor

Swap the placeholder values for ACCOUNT_SID and AUTH_TOKEN with your personal Twilio credentials. Go to https://www.twilio.com/console(link takes you to an external page) and log in. On this page, you'll find your unique Account SID and Auth Token, which you'll need any time you send messages through the Twilio client like this.

Open Example.java and replace the values for ACCOUNT_SID and AUTH_TOKEN with your unique values.

(error)

Danger

Please note: it's okay to hardcode your credentials when getting started, but you should use environment variables to keep them secret before deploying to production. Check out how to set environment variables(link takes you to an external page) for more information.

Replace the "to" phone number

replace-the-to-phone-number page anchor

Replace the first phone number in Example.java with your mobile phone number. This can be any phone number that can receive text messages, but it's a good idea to test with your own phone so you can see the magic happen! You should use E.164 formatting for this value:

[+][country code][phone number including area code]

Replace the "from" phone number

replace-the-from-phone-number page anchor

Remember that SMS-enabled phone number you obtained just a few minutes ago? Go ahead and replace the second phone number in Example.java with that one, making sure to use E.164 formatting as before.

Save your changes and compile this Java class from your terminal, replacing 8.0.0 with the relevant version number:

javac -cp twilio-8.0.0-jar-with-dependencies.jar Example.java

We need to include that Twilio jar with the dependencies to compile our class from the command line. If you are using an Integrated Development Environment (IDE) such as IntelliJ IDEA, Netbeans or Eclipse, you can add that Twilio jar to your classpath or your project libraries like any other dependency. You can also use a build tool like Maven or Gradle to build and run your Java application - just specify Twilio's helper library as a dependency.

Once you have the Java class built, you will need to run it - if you are running it from the command line on macOS or Linux, the command will look like this:

java -cp .:twilio-8.0.0-jar-with-dependencies.jar Example

On Windows, the equivalent command looks like this:

java -cp ".;twilio-8.0.0-jar-with-dependencies.jar" Example

The difference is that on Windows, the Java classpath separator on the command line is a semicolon, and on macOS or Linux, it is a colon.

That's it! In a few moments, you should receive an SMS from your Twilio number on your phone.

Are your customers in the U.S. or Canada? You can also send them MMS messages by adding just one line of code. Check out this guide to sending MMS to see how it's done.

(warning)

Warning

If you are on a Twilio Trial account, your outgoing SMS messages are limited to phone numbers that you have verified with Twilio. Phone numbers can be verified via your Twilio Console's Verified Caller IDs(link takes you to an external page).


Receive and reply to inbound SMS messages

receive-and-reply-to-inbound-sms-messages page anchor

When your Twilio number receives an incoming message, Twilio will send an HTTP request to a server you control. This callback mechanism is known as a webhook. When Twilio sends your application a request, it expects a response in the TwiML XML format telling it how to respond to the message.

Let's see how we would build this in Java using the Spark(link takes you to an external page) web application framework. Spark is a lightweight web application framework and is completely different from the big data software named Apache Spark.

Spark requires its own library, separate from the Twilio Java helper library, which you can install using the directions on the Download Spark Java(link takes you to an external page) page. You'll find directions for using Spark with Maven, Gradle, or as a standalone download. Spark does not come with a logging implementation, but it does work with the Simple Logging Facade 4 Java (SLF4J)(link takes you to an external page), which you can also include in your Java classpath.

You can certainly set up all of your dependencies on the command line like we did when we sent the SMS through Twilio above, but it's a little easier to get everything set up using a Java integrated development environment (IDE). We are going to use the free, community edition of IntelliJ IDEA, which you can download from JetBrains(link takes you to an external page). You can download JAR files and use them directly with IntelliJ IDEA, or you can use a dependency manager such as Maven or Gradle. We will guide you through using IntelliJ IDEA with Maven or Gradle to build our application.


Creating a web application with IntelliJ IDEA and Gradle

creating-a-web-application-with-intellij-idea-and-gradle page anchor

If you haven't downloaded and installed IntelliJ IDEA Community Edition(link takes you to an external page), please go ahead and do that now! After you open IDEA, create a new project and select Maven or Gradle as the build system.

In addition, verify that IntelliJ IDEA has a project JDK (you'll need Java 8 or higher, so version 1.8 or above). You can use the default settings for other options.

Once we've got our project all set up, we just have a few more steps! We'll need the Twilio Java helper library, and the Spark Java web application framework as dependencies, along with the logging implementation so that we can see status messages from Spark.


Follow Maven's(link takes you to an external page) or Gradle's(link takes you to an external page) instructions to add the following dependencies:

com.twilio.sdk
com.sparkjava
org.slf4j
With these three dependencies, Maven or Gradle will download the appropriate libraries for you and add them to the classpath for building and running your Java application.

Now that we have all of that out of the way, it's time to write some code!


Responding to an incoming text message

responding-to-an-incoming-text-message page anchor

We'll need to start by creating a Java class in our project. In IntelliJ IDEA, select the java folder under src and main. Next, open the File menu at the top of the screen. Choose the New submenu, and then Java Class.

A small popup window will show, and you can create a new class. Name your class SmsApp - capitalization is important because it has to match the code sample.

You should have an SmsApp.java source code file now. Copy and paste the code from the code sample into that source code file.

This Java code will listen for inbound HTTP GET requests to '/', respond with "Hello Web," and listen to inbound HTTP POST requests for '/sms', and respond with TwiML markup for an SMS Message.

1
import com.twilio.twiml.MessagingResponse;
2
import com.twilio.twiml.messaging.Body;
3
import com.twilio.twiml.messaging.Message;
4
5
import static spark.Spark.*;
6
7
public class SmsApp {
8
public static void main(String[] args) {
9
get("/", (req, res) -> "Hello Web");
10
11
post("/sms", (req, res) -> {
12
res.type("application/xml");
13
Body body = new Body
14
.Builder("The Robots are coming! Head for the hills!")
15
.build();
16
Message sms = new Message
17
.Builder()
18
.body(body)
19
.build();
20
MessagingResponse twiml = new MessagingResponse
21
.Builder()
22
.message(sms)
23
.build();
24
return twiml.toXml();
25
});
26
}
27
}

After you get your code in place, you can right-click on SmsApp class in the project outline on the left-hand side, and then choose the Run 'SmsApp.main()' menu item.

The Java spark web application server will start listening on port 4567. You can try it out by going to http://localhost:4567/(link takes you to an external page) in your web browser.

(warning)

Warning

One important thing to note - if you make a change to your code, and want to run the server again, you will need to stop the currently running application with the red stop button. Only one application can use port 4567 at a time, so if you run your Java application while an older version is still running, the new application will immediately exit.

That's all the code you need - there's just one more step before everything is wired up.

Configure ngrok and your webhook URL

configure-ngrok-and-your-webhook-url page anchor

We'll use ngrok to set up a tunnel from the public internet to your localhost. This will let us use a public URL as the webhook for your application.

First, download and configure ngrok(link takes you to an external page).

Next, run this command to have ngrok set up a tunnel to your localhost:

ngrok http 4567

This will start an ngrok tunnel. Copy down the Forwarding URL that ends with ngrok.io.

Then, you need to configure your Twilio phone number to call your webhook URL whenever a new message comes in:

  1. Go to Phone Numbers > Active Numbers in the Twilio Console(link takes you to an external page) .
  2. Select the SMS-enabled Twilio number you want to use.
  3. For the A MESSAGE COMES IN webhook, enter the ngrok URL you copied down earlier. Append /sms to the end of the URL.
Screenshot showing how to configure webhook URL with ngrok URL in console.

Test your application with a text

test-your-application-with-a-text page anchor

Now that everything is glued together, it's time to test.

Send a text message from your mobile phone to your Twilio phone number. Twilio will forward your response back as an SMS!


Now that you know the basics of sending and receiving SMS text messages with Java, you might want to check out these resources.

Happy hacking!

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.