Sending SMS with Java with Twilio

March 23, 2021
Written by
Reviewed by

Title: Sending SMS with Java and Twilio

Did you know you can code a Java app in under 5 minutes to send an SMS using the Twilio API? Probably closer to 2, once you've got the tools installed. You'll need:

The easiest way to call the Twilio API is with the Twilio Java Helper Library. In this I'll give examples using the Apache Maven build tool which will download and manage the dependency and packaging the project. You can get up to speed with Maven in 5 Minutes, and other tools like Gradle will work too, if that's what you prefer.

If you prefer watching to reading then check out my Twilio 2 Minute Demo video:

Creating a new project

I'll assume you're starting from scratch with an empty directory, so the first step is to create a new project.

A new Maven Project

Create a new Maven project in IntelliJ IDEA like this:

Screenshot of IDE New Maven Project wizard. An equivalent setup is described as a code snippet in the prose.

I like to use the IDE's built-in New Project wizard, but it's also possible to create the same from the command line by creating a folder for your source code in the standard directory layout with mkdir -p src/main/java and creating a file called pom.xml with this content:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>java-send-sms</artifactId>
    <version>1.0-SNAPSHOT</version>

</project>

[this code on GitHub]

Before getting to coding we need to tell Maven to use Java 8, and to download the Twilio Helper Library.  Add the following to the pom.xml as the last thing before </project>:

<properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
    <dependency>
        <groupId>com.twilio.sdk</groupId>
        <artifactId>twilio</artifactId>
        <version>8.10.0</version>
    </dependency>
</dependencies>

We always recommend using the latest version of the Twilio Helper Library. At the time of writing this is 8.10.0 but you can always check the latest version at mvnreporistory.com.

Writing the code

Maven uses src/main/java as the place to put your Java source code. Inside that, create a package called com.example and a class in there called TwilioSendSms. Your directory structure should be:

├── pom.xml
└── src
    └── main
        └── java
            └── com
                └── example
                    └── TwilioSendSms.java

Start off the TwilioSendSms class with a main method:

package com.example;

public class TwilioSendSms {

    public static void main(String[] args) {
        // code will go in here
    }
}

[this code on GitHub]

Where it says // code will go in here, you need to do two things:

  • Authenticate the Twilio client
  • Call the API to send an SMS

These will take one line of code each.

Authenticate the Twilio client

You'll need your ACCOUNT_SID and AUTH_TOKEN from your Twilio Console. To help keep these secret I'd always recommend reading these from environment variables rather than hard-coding them.  I use the EnvFile plugin for IntelliJ IDEA, and there are alternatives for other IDEs or you can set them in your OS. Once they are set in the environment, add this code in the main() function body:

Twilio.init(
    System.getenv("TWILIO_ACCOUNT_SID"),
    System.getenv("TWILIO_AUTH_TOKEN"));

If you have not set the environment variables this code will throw

com.twilio.exception.AuthenticationException: Username can not be null

Send your first SMS

At last - the code for sending a text message!  Add this to the main method, below the init code you just added:

Message.creator(
    new PhoneNumber("<TO number - ie your cellphone>"),
    new PhoneNumber("<FROM number - ie your Twilio number"),
    "Hello from Twilio 📞")
  .create();

[this code (with imports) on GitHub]

The phone numbers you pass to the PhoneNumber constructors need to be real phone numbers, in E.164 format. Once you've added them in, run the code and voilà!

Screenshot of my phone&#x27;s SMS app showing a message that says "Hello from Twilio 📞"

🎉🎉🎉 Congratulations 🎉🎉🎉

Wrapping up

Now you know how to send an SMS using the Twilio API, the next thing might be receiving and responding to SMS from Java.

It's time to put your imagination to work. You can send daily reminders, weather forecasts, alerts for parking spaces, or anything else you can imagine.

Whatever you're building, I'd love to hear about it - get in touch

I can't wait to see what you build!