Sending Text Messages via Twilio/Python

Steven Kyle
3 min readDec 5, 2021
Photo by Maxim Ilyahov on Unsplash

In this blog post I am going to introduce a useful tool that will let you send text message via Twilio/Python. This would come in handy for any application that monitors the status of a certain item/condition that needs to immediately notify you. One such example could be that you need to closely monitor a stock price while day trading.

Twilio

To send text messages we will be using the services of Twilio. Twilio comes with a free trial that will let you use SMS messaging. To sign up, you can follow this link to the Twilio website. Once you make an account it will prompt you to verify your email and phone number. Once verified, just follow the onscreen instructions on what project you are creating. When everything is set up, you will be able to obtain a free phone number for the trial duration.

Now that you have your account set up, we can go ahead and start coding. The information you’re going to need from the Twilio website will be:
— Account SID
— AUTH Token
— Twilio phone number

*** MAKE SURE TO KEEP YOUR ACCOUNT SID AND AUTH TOKEN HIDDEN, DO NOT ACCIDENTALLY PUSH IT UP TO GITHUB***

Install/Importing Packages

To communicate with the Twilio API we will need to install the twilio package. We will use pip to install this. The following line can be used in the command line.

pip install twilio

Once installed we can call upon the library in our code using this line.

from twilio.rest import Client

Sending Texts

To send texts we will have to use the imported Client and use our own account sid and auth token. These can be found on your twilio account, and remember to always keep these secret. After that we can generate a text message by calling upon the client, client.messages.create we can then pass the recipients phone number (to), the twilio phone number (from_) and then finally the actual text message (body). The code below runs through an example. Make sure to include your country code when inputing the phone numbers (US is +1). Below the example picture is the identical code that is formatted to let you easily copy and paste.

# Importing packages
from twilio.rest import Client
account_sid = 'Input your sid number here'
auth_token = 'Input your auth token here'
# Connecting to API client
client = Client(account_sid, auth_token)
# Creating and sending messages
client.messages.create(to = 'Insert own phone number',
from_ = 'Insert Twilio phone number',
body = 'This is a test message')

--

--

Steven Kyle

25 year old Texan in the midst of a career change into DataScience.