How to Send an SMS With Python Using Twilio

October 05, 2016
Written by

How to send an SMS in Python

All you need to send an SMS with Python using Twilio are the following twelve lines of code:

import os
from twilio.rest import Client


account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
auth_token = os.environ.get('TWILIO_AUTH_TOKEN')

client = Client(account_sid, auth_token)

client.messages.create(from_=os.environ.get('TWILIO_PHONE_NUMBER'),
                      to=os.environ.get('CELL_PHONE_NUMBER'),
                      body='You just sent an SMS from Python using Twilio!')

If you’d like to see this in action, check out this short video:

More of a Textual Learner? Here’s a Walkthrough

The first thing we need for the above code to work is a Twilio account. Sign up for your free trial account here.

We also need an SMS-enabled phone number. You can search for and buy one in the Twilio console.

Sending an SMS using Twilio is as simple as making an HTTP POST request to the /Messages resource in the Twilio API. Twilio makes this super simple by providing a helper library. Install the twilio library from the terminal using pip:

pip install twilio

Next, create a file named sms.py and open it in your favorite text editor. At the top of the file import os and TwilioRestClient from twilio.rest. In the code below we use os to read our Twilio credentials from system environment variables and create a TwilioRestClient using them. If you’re unsure how to store your Twilio credentials in environment variables click here for Windows or here for Mac OS X for more information.

import os
from twilio.rest import Client


account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
auth_token = os.environ.get('TWILIO_AUTH_TOKEN')

client = Client(account_sid, auth_token)

Use the client to send an SMS message from your Twilio number to your cell phone. Make sure to replace the phone number placeholders with your Twilio and cell phone numbers:

client.messages.create(from_=os.environ.get('TWILIO_PHONE_NUMBER'),
                       to=os.environ.get('CELL_PHONE_NUMBER'),
                       body='You just sent an SMS from Python using Twilio!')

Head back to the terminal and run the script:

python sms.py

In just a few seconds you should receive your text message!

SMS sent from Python code received on an iPhone

Conclusion

If you’d like to learn more about using Twilio and Python together check out:

What are you building? I’d love to hear about it. You can reach me on Twitter @brentschooley or drop me an email at brent@twilio.com.