How to Send SMS From a MySQL Database With Java Spring Boot

December 02, 2022
Written by
Diane Phan
Twilion
Reviewed by

header - How to Send SMS From a MySQL Database With Java Spring Boot

This is part 3 of the series of how to set up a working MySQL database to send SMS. Part 2 can be found under the tutorial requirements.  

In this article, you will learn how to send an SMS with contents from a MySQL database.  

Tutorial requirements

Add the Twilio dependencies

At this point, you should have a functioning MySQL database running on a Spring Boot web application.

Navigate to the pom.xml file to add the following text to include dependencies in your project:

    <dependencies>
        <dependency>
            <groupId>com.twilio.sdk</groupId>
            <artifactId>twilio</artifactId>
            <version>9.0.0-rc.5</version>
        </dependency>
    </dependencies>

This dependency allows the Twilio Java Helper Library to be used and executed in this Maven project. This is essential for the controller class that will be created later on to handle the TwiML messages of this SMS project.  

We always recommend using the latest version of the Twilio Helper Library. At the time of writing the latest version is 9.0.0-rc.5 but new versions are released frequently. You can always check the latest version at mvnreporistory.com.

Save the file.

Look at the top-right corner of the IntelliJ IDEA and find the little icon with an "M" shape. Click it to load Maven changes.

An icon with an "M" shape with a tooltip "Load Maven Changes"

Configure the environment variables

Locate the Run tab at the top of the IntelliJ IDEA console and select Edit Configurations… in the dropdown as seen below:

edit configurations option in intellij idea

This image is reused and the project directory name does not reflect the one used in this project.

Another window displaying the "Run/Debug Configurations" will pop up with the details regarding the project.

If there are no existing configurations for you to edit, click on Add New… on the left-hand side and create a new application named "JavadbApplication".

option to add a new application to edit configurations in intellij idea

You can find your account credentials on the Twilio Console.

Twilio credentials in the Console

Refer to this article to set up and hide variables in the IntelliJ IDEA environment.

It is best practice to set the Twilio credentials as environment variables. You might also want to store both your Twilio phone number and personal phone number as environmental variables. This would be helpful in the case that the code is shared on a public repository so that the phone numbers are not exposed.

Go ahead and follow the same instructions to store your phone number as the PHONE_NUMBER key in the IntelliJ IDEA environment. This must be stored in E.164 format such as "+19140201400".

Since a Messaging Service is used to schedule the SMS, another variable named TWILIO_MESSAGING_SERVICE_SID must also be created. You can find it in the Messaging Services page of the Twilio Console. This identifier starts with the letters MG.

edit the configurations to build and run the java application

This image is reused and the project application name does not reflect the one used in this project.

Click on the Apply button, and then OK once finished.

Send an SMS with Java

By now, you should have a functional MySQL database running on a Java Spring Boot application.

Navigate to the QuoteController.java file and add the following route to the REST controller:

    @GetMapping(value = "/sms")
    @ResponseBody
    public String sendSMS() {
        long min = 1;
        long max = 6;
        long random = (long)(Math.random()*(max-min+1)+min);

        Quote quote = quoteRepository.findById(random).get();
        String returnString = quote.getQuote();
        Message message = Message.creator(
                        new com.twilio.type.PhoneNumber(PHONE_NUMBER),
                        TWILIO_MESSAGING_SERVICE_SID,
                        returnString)
                .create();
        LOG.info("Message SID is {}", message.getSid());
        return message.getSid() + " sent successfully";
    }

The sendSMS() function uses the quoteRepository to look up a random quote from the database. The quote is retrieved in string format then constructed in a message instance of the Message resource as provided by the Twilio REST API in order to send an SMS to your personal phone number from your Twilio phone number. Make sure to replace those placeholders with the appropriate values.

After the message is sent, the message SID is printed on your terminal for your reference.

Run the spring boot application

If you have not done so already, navigate to the JavadbApplication.java file to click on the green play button next to the public class definition. Select the Run option.

Wait a few seconds for the project to build, download the project's dependencies, and compile.

Here is the completed code in a separate branch on the javadb GitHub repository for your reference.

Enter the URL http://localhost:8080/sms to navigate to the sms route and trigger the sendSMS() function. You will see a screen similar to the screenshot below:

localhost:8080/sms

Look at your mobile device and you should see a random quote from your database:

screenshot of messeages that twilio sent to the reader

Refreshing the URL will fire another random SMS and display the message SID on the web browser.

What's next for sending SMS from a MySQL database?

Congratulations on sending an SMS with content from a MySQL database! Consider taking this project one step further and figuring out how to respond to inbound messages from the user, storing their messages in the database, or scheduling the SMS.

Let me know about the projects you're building with Java and Twilio SMS by reaching out to me over email!

Diane Phan is a developer on the Twilio Voices team. She loves to help programmers tackle difficult challenges that might prevent them from bringing their projects to life. She can be reached at dphan [at] twilio.com or LinkedIn.