Menu

Expand
Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

Programmable SMS Quickstart for Java

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.

Show me how it's done!

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

You can sign up for a free Twilio trial account here.

  • 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 to create a project. For the sake of this tutorial, you can click on the "Learn and Explore" template. Give your project a name, or just click "skip remaining steps" to continue with the default.
  • Once you get through the project creation flow, you'll arrive at your project dashboard in the Twilio Console. This is where you'll be able to access your Account SID an authentication token, find a Twilio phone number, and more.
I've got an account! What's next?

Install the Twilio CLI

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

One of the easiest ways to install the CLI on Mac OS X is to use Homebrew. If you don't already have it installed, visit the Homebrew site for installation instructions and then return here.

Once Homebrew is installed, simply run the following command to install the CLI:

brew tap twilio/brew && brew install twilio

Updating

If you already installed the CLI with brew and want to upgrade to the latest version, run:

brew upgrade twilio

Before we can install, we need to make sure you have Node.js installed (version 8 or above). To see if you have node installed, try running this command:

node -v

If your system reports v8.0.0 or above, you can skip the next step.

Installing Node.js on Windows

Using the Windows Installer (.msi) is the recommended way to install Node.js on Windows. You can download the installer from the Node.js download page.

Installing Twilio CLI

The CLI is installed with npm (Node Package Manager), which comes with Node.js. To install the CLI run the following command:

npm install twilio-cli -g

Note the -g option is what installs the command globally so you can run it from anywhere in your system.

Updating

If you already installed the CLI with npm and want to upgrade to the latest version, run:

npm install twilio-cli@latest -g

Before we can install, we need to make sure you have Node.js installed (version 8 or above). Even if you already installed Node yourself, the CLI works best when you install it using nvm. Here's how to get nvm installed on most Linux systems:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash

Please visit the nvm installation instructions for additional options and troubleshooting steps. Once you have nvm installed, run the following to install and use the most recent LTS release of Node.js:

nvm install --lts
nvm use <insert version reported from above>

Installing other Twilio CLI prerequisites for Linux

Depending on your distribution, you will need to run one of the following commands:

  • Debian/Ubuntu: sudo apt-get install libsecret-1-dev
  • Red Hat-based: sudo yum install libsecret-devel
  • Arch Linux: sudo pacman -S libsecret

Installing Twilio CLI

The CLI is installed with npm (Node Package Manager), which comes with Node.js. To install the CLI run the following command:

npm install twilio-cli -g

Note the -g option is what installs the command globally so you can run it from anywhere in your system.

Updating

If you already installed the CLI with npm and want to upgrade to the latest version, run:

npm install twilio-cli@latest -g

Run twilio login to get the Twilio CLI connected to your account. Visit https://www.twilio.com/console, and you’ll find your unique Account SID and Auth Token to provide to the CLI.

You can reveal your auth token by clicking on the eyeball icon:

Reveal Your Auth Token

Now to get a phone number...

Get a phone number

If you don't currently own a Twilio phone number with SMS functionality, you'll need to purchase one. With the CLI, run:

twilio phone-numbers:buy:local --country-code US --sms-enabled

Replace US with your ISO-3166-1 country code if you would like a phone number in another country. If you aren't finding any SMS enabled numbers, try looking for a mobile number instead of a local number: twilio phone-numbers:buy:mobile --country-code DE --sms-enabled

Select a phone number to add it to your account.

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

No problem! Take me through the setup.

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 7 or higher, which will appear as version number "1.7" 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.

Download the standalone Twilio Java helper library

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

Next, download the standalone Twilio Java Helper Library. 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-7.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 using a build automation tool.

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.

All set! Let's send a text message.

Send an outbound SMS message with Java

Now that we have the JDK setup 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 SmsSender.java and type or paste in this code sample.

        
        
        
        
        This code creates a new instance of the Message resource and sends an HTTP POST to the Messages resource URI.

        Send an SMS using Twilio with Java

        This code creates a new instance of the Message resource and sends an HTTP POST to the Messages resource URI.

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

        Replace the placeholder credential values

        Swap the placeholder values for ACCOUNT_SID and AUTH_TOKEN with your personal Twilio credentials. Go to https://www.twilio.com/console 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. You can reveal your auth token by clicking on the eyeball icon:

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

        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 for more information.

        Replace the "from" phone number

        Remember that SMS-enabled phone number you bought just a few minutes ago? Go ahead and replace the existing from number with that one, making sure to use E.164 formatting:

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

        Replace the "to" phone number

        Replace the to phone number 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! As above, you should use E.164 formatting for this value.

        Save your changes and compile this Java class from your terminal:

        javac -cp twilio-7.45.0-jar-with-dependencies.jar SmsSender.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 simply 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-7.45.0-jar-with-dependencies.jar SmsSender
        

        On Windows, the equivalent command looks like this:

        java -cp ".;twilio-7.45.0-jar-with-dependencies.jar" SmsSender
        

        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.

        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.

        I sent the message! How do I receive them?

        Receive and reply to inbound SMS messages

        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 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 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), 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. 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 use Gradle with IntelliJ IDEA to build our application.

        Creating a web application with IntelliJ IDEA and Gradle

        If you haven't downloaded and installed IntelliJ IDEA Community Edition, please go ahead and do that now! After you run IDEA for the first time, you will see a screen that looks like this:

        Start IDEA

        Choose 'Create New Project,' and the new New Project wizard will start:

        New Gradle Project with IntelliJ IDEA

        On the left-hand side of that dialog box, choose Gradle (instead of Java), so that IntelliJ IDEA will set your project up to use Gradle for dependency management. You could also choose to use Maven here instead - the process is almost the same.

        After choosing Gradle, verify that IntelliJ IDEA has a project SDK (you'll need Java 8 or higher, so version 1.8 or above), and then click Next.

        IntelliJ IDEA Project Name

        On the next screen in the wizard, you will be asked for a group id, an artifact id, and a version number. For the group id, you can use a reverse domain name, such as com.yourcompany.sms, and for the artifact id, you should use your project name, like sms-quickstart-app. You can leave the version as 1.0-SNAPSHOT. After filling in these fields, click Next.

        Gradle Settings

        On this Gradle settings screen, you can leave the defaults and then click Next.

        IntelliJ IDEA Project Creation

        Last, you can confirm the project name and project directory to use for your Quickstart web application. The defaults are probably fine here as well. Clicking Finish will take you to your new IntelliJ Project. If you just installed IntelliJ IDEA, the IDE will download Gradle and do some setup and installation.

        IntelliJ IDEA Project Created

        Now that 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. With Gradle, we can add those to the build.gradle file that IntelliJ created for us. Go ahead and find build.gradle in the sidebar and click on it to open it.

              
              
              
              

              Adding dependencies in build.gradle

              You'll need to add three lines to your build.gradle file, in the dependencies group:

              compile group: "com.twilio.sdk", name: "twilio", version: "7.45.+"
              compile group: "com.sparkjava", name: "spark-core", version: "2.7.1"
              compile group: "org.slf4j", name: "slf4j-simple", version: "1.7.21"

              With these three dependencies, 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

              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.

                    
                    
                    
                    
                    When your Twilio phone number receives an incoming message, Twilio will send an HTTP request to your server. This code shows how your server can reply with a text message using the Twilio helper library.

                    Respond to an incoming text message

                    When your Twilio phone number receives an incoming message, Twilio will send an HTTP request to your server. This code shows how your server can reply with a text message using the Twilio helper library.

                    After you get your code in place, you can right-click on the 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/ in your web browser.

                    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.

                    I'm getting excited now - let's connect our Java to Twilio!

                    Configure your Webhook URL

                    Now, you need to configure your Twilio phone number to call your webhook URL whenever a new message comes in. Just run this CLI command, replacing the phone number with your Twilio phone number:

                    twilio phone-numbers:update "+15017122661" --sms-url="http://localhost:4567/sms"
                    

                    The CLI will start an ngrok tunnel (so Twilio can reach your development machine) and wait patiently for incoming text messages!

                    Test your application with a text

                    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!

                    It worked! All done - what's next?

                    Where to next?

                    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!

                    Rate this page:

                    Need some help?

                    We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.