Send Scheduled SMS with Python and Twilio

January 20, 2022
Written by
Reviewed by
Paul Kamp
Twilion

Send Scheduled SMS with Python and Twilio

Twilio is all about powering communication – and doing it conveniently and fast. Our Programmable Messaging service has been available for a long time, but until now, scheduling a message to be sent at a future time required a developer to use their own scheduling solution.

Fortunately, this is now a thing of the past! With Message Scheduling, you can send your scheduled SMS and MMS messages with a single API call, without using custom schedulers.

In this tutorial, you’ll learn how to send scheduled SMS notifications in Python.

Tutorial requirements

Buy a Twilio phone number

If you haven't done so already, your first task is to purchase a Twilio phone number to send SMS.

Log in to the Twilio Console, select Phone Numbers, and then click on the “Buy a number” button to buy a Twilio number. Note that if you have a free account, you will be using your trial credit for this purchase.

On the “Buy a Number” page, select your country and check SMS in the “Capabilities” field. If you’d like to request a number that is local to your region, you can enter your area code in the “Number” field.

Buy a Twilio phone number

Click the “Search” button to see what numbers are available, and then click “Buy” for the number you like from the results. After you confirm your purchase, click the “Close” button.

Configure a Messaging Service

Scheduled messages can only be sent from a Messaging Service at this time, so the next step is to configure one and add your Twilio phone number to it.

Still in the Console, find the “Messaging” product and click on its Services option. Then click the “Create Messaging Service” button.

On the first page of the creation process, enter a friendly name for the service, such as “Appointments”, and select “Notify my users” in the “Select what you want to use Messaging for” dropdown.

Create messaging service page 1

Click the “Create Messaging Service” button to move to the second step.

In this part of the configuration, you have to add the sender phone number(s) to the sender pool used by the service. Click the “Add Senders” button to add the Twilio phone number you acquired in the previous section.

Create messaging service part 2

Select Phone Number in the “Sender Type” dropdown, and click “Continue”.

Add a checkmark next to the phone number you want to use as a sender, and click “Add phone numbers”.

Add senders to messaging service

Click the “Step 3: Set up integration” button to move on to the next step. You don’t have to change any of the settings on this page, just click on “Step 4: Add compliance info”.

To complete the configuration of your Messaging Service, click on “Complete Messaging Service Setup”. You will now be offered the option to send a test message.

Messaging service setup complete

It is a good idea to test that your messaging service is able to send messages, so go ahead and click on “Try sending a message”.

In the “To phone number” pulldown, select your personal number, which should be registered and verified with your Twilio account. In the “From Messaging Service SID”, select the Messaging Service you just created. In the “Body Text” enter some text to send yourself.

Send test SMS

Click the “Send test SMS” button, and make sure you receive the SMS on your phone.

Python project setup

In this section, you are going to set up a brand new Python project. To keep things nicely organized, open a terminal or command prompt, find a suitable place, and create a new directory where the project you are about to create will live:

mkdir python-scheduled-sms
cd python-scheduled-sms

Create a virtual environment

Following Python best practices, you are now going to create a virtual environment, where you are going to install the Python package needed for this project.

If you are using a Unix or Mac OS system, open a terminal and enter the following commands:

python3 -m venv venv
source venv/bin/activate

If you are following the tutorial on Windows, enter the following commands in a command prompt window:

python -m venv venv
venv\Scripts\activate

With the virtual environment activated, you are ready to install the Twilio helper library for Python:

pip install twilio

To send an SMS with Twilio, the Python application needs to have access to your Twilio account credentials to authenticate. Also, it will need the SID associated with the Message Service you just created.

The most convenient way to define these configuration values is to set environment variables for them. In a bash or zsh session, you can configure these settings as follows:

export TWILIO_ACCOUNT_SID=xxxxxxxxx
export TWILIO_AUTH_TOKEN=xxxxxxxxx
export TWILIO_MESSAGING_SERVICE_SID=xxxxxxxxx

If you are following this tutorial on Windows, use set instead of export in your command prompt window.

You will need to replace all the xxxxxxxxx placeholders with the correct values that apply to your account. The first two variables are your Twilio “Account SID” and your “Auth Token”. You can find them in the dashboard of the main page of the Twilio Console, under “Account Info”:

Twilio credentials in the Console

The TWILIO_MESSAGING_SERVICE_SID variable is the SID assigned to the Messaging Service. You can find it in the Messaging Services page of the Twilio Console. This identifier starts with the letters MG.

Send a scheduled SMS with Python

You are now ready to start coding the Python application.

Open a new file named scheduled_sms.py in your text editor or IDE and enter this code in it:

from datetime import datetime, timedelta
import os
from twilio.rest import Client

# create a Twilio client
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)

# schedule message to be sent 61 minutes after current time
send_when = datetime.utcnow() + timedelta(minutes=61)

# send the SMS
messaging_service_sid = os.environ['TWILIO_MESSAGING_SERVICE_SID']
message = client.messages.create(
    from_=messaging_service_sid,
    to='+1xxxxxxxxxx',  # ← your phone number here
    body='Friendly reminder that you have an appointment with us next week.',
    schedule_type='fixed',
    send_at=send_when.isoformat() + 'Z',
)

print(message.sid)

This short application creates an instance of the Twilio client object and initializes it with the Account SID and Auth Token values that come from the environment variables you configured earlier.

The send_when variable is set to a datetime object that represents the time at which the SMS should be sent. The Message Scheduling feature currently requires that this time is more than 15 minutes and less than 35 days ahead. Since this is just an exercise, I set the delivery time to be 61 minutes later, to get the SMS as quickly as possible.

The client.messages.create() function is used to create and schedule the SMS. This function takes the standard from_, to and body arguments to define the sender, recipient, and body of the SMS, respectively. These arguments are the same for both immediate and scheduled sends. Note that from_ ends with an underscore because from is a reserved keyword in Python.

For the from_ argument, the SID of the Messaging Service is used. For to, enter your personal phone number in E.164 format. The body argument can be anything you’d like to send yourself.

The remaining two arguments are used to tell Twilio that this SMS should be sent at a later time. The schedule_type argument configures the type of scheduling that you want to use. As I’m writing this, the only allowed value for this argument is the string ’fixed’. The send_at argument configures the time when the message should be sent. This argument must be given in ISO 8601 format. In Python, the datetime.isoformat() method can be used to obtain the required format, but it is important to note that by default, datetime objects in Python do not have a timezone associated with them. The Z added at the end specifies the UTC timezone. If you use datetime objects that are timezone aware, then do not append the Z. If you use datetime objects that are not timezone aware, but they are not in UTC, then append the appropriate timezone code, according to the ISO 8601 specification.

The application prints the sid value assigned to the scheduled message. This is an identifier that you can use to cancel the message if you need to.

Ready to try this out?

Make sure you’ve entered your own phone number for the to argument of the client.messages.create call, and then run the Python script in the root directory of the project as follows:

python scheduled_sms.py

You should see a code printed to the terminal that starts with the letters SM. This is the identifier of your message. If you see this code, then you know that the message was successfully scheduled.

Now you have to wait 61 minutes to receive this SMS on your phone! In the meantime, you can view the message in the Programmable Messaging Logs section of the Twilio Console, under which the message will show with its status set to “Scheduled” until the time of delivery.

Programmable Messaging Logs before delivery

When the hour passes and your SMS is delivered, the status of the message will change to “Delivered”. You will also be able to see your Twilio phone number as the sender.

Programmable Messaging Logs after delivery

Next steps

Congratulations on learning how to send scheduled SMS with Python! There are a number of resources on scheduling SMS that you may want to review to learn more:

I’d love to see what you build with Twilio and Message Scheduling!

Miguel Grinberg is a Principal Software Engineer for Technical Content at Twilio. Reach out to him at mgrinberg [at] twilio [dot] com if you have a cool project you’d like to share on this blog!