Twilio SMS Python Quickstart

With just a few lines of code, your Python application can send and receive text messages with Twilio Programmable SMS.

This Python SMS Quickstart will teach you how to do this using our Communications REST API, the Twilio Python helper library, and Python’s Flask microframework to ease development. If you prefer using Django, check out this blog post.

In this Quickstart, you will learn how to:

  1. Sign up for Twilio and get your first SMS-enabled Twilio phone number
  2. Set up your development environment to send and receive messages
  3. Send your first SMS
  4. Receive inbound text messages
  5. Reply to incoming messages with an SMS

Prefer to get started by watching a video? Check out our Python SMS Quickstart video on Youtube.

Sign up for Twilio and Get a Phone Number

If you already have a Twilio account and an SMS-enabled Twilio phone number, you’re all set here! Feel free to jump to the next step.

Before you can send an SMS from Python, you'll need to sign up for a Twilio account or sign into your existing account and purchase an SMS-capable phone number.

If you don't currently own a Twilio phone number with SMS functionality, you'll need to purchase one.  After navigating to the Buy a Number page, check the "SMS" box and click "Search."

Buy a SMS-Capable Twilio Phone Number

You’ll then see a list of available phone numbers and their capabilities. Find a number that suits your fancy and click "Buy" to add it to your account.

Select an SMS-enabled phone number

Now that you have a Twilio account and a programmable phone number, you can start writing some code! To make things even easier, we'll next install Twilio's official helper for Python applications.

Install Python and the Twilio Helper Library

If you’ve gone through one of our other Python Quickstarts already and have Python and the Twilio Python helper library installed, you can skip this step and get straight to sending your first text message.

To send your first SMS, you’ll need to have Python and the Twilio Python helper library installed.

Install Python

If you’re using a Mac or Linux machine, you probably already have Python installed. You can check this by opening up a terminal and running the following command:

python --version

You should see something like:

$ python --version
Python 3.4  # Python 2.7+ is okay too

Windows users can follow this excellent tutorial for installing Python on Windows.

Twilio’s Python SDK supports both Python 2 and Python 3. You can use either version for this quickstart, but we recommend using Python 3 for future projects with Twilio unless there are specific libraries your project needs which are only compatible with Python 2.

Install the Twilio Python Helper Library

The easiest way to install the library is using pip, a package manager for Python that makes it easier to install the libraries you need. Simply run this in the terminal:

pip install twilio

If you get a pip: command not found error, you can also use easy_install by running this in your terminal:

easy_install twilio

If you'd prefer a manual installation, you can download the source code (ZIP) for twilio-python and then install the library by running:

python setup.py install

in the folder containing the twilio-python library.

Send an Outbound SMS with Python

Now that we have Python and twilio-python installed, we can send an outbound text message from the Twilio phone number we just purchased with a single API request. Create and open a new file called send_sms.py and type or paste in this code sample.

Loading Code Samples...
Language
SDK Version:
  • 5.x
  • 6.x
# /usr/bin/env python
# Download the twilio-python library from twilio.com/docs/libraries/python
from twilio.rest import TwilioRestClient

# Find these values at https://twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"

client = TwilioRestClient(account_sid, auth_token)

client.messages.create(
    to="+12316851234",
    from_="+15555555555",
    body="Hello there!")
# /usr/bin/env python
# Download the twilio-python library from twilio.com/docs/libraries/python
from twilio.rest import Client

# Find these values at https://twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"

client = Client(account_sid, auth_token)

client.api.account.messages.create(
    to="+12316851234",
    from_="+15555555555",
    body="Hello there!")
This code creates a new instance of the Message resource and sends an HTTP POST to the Messages resource URI.
Send an SMS Using Twilio

This code creates a new instance of the Message resource and sends an HTTP POST to the Messages resource URI.

You’ll need to edit this file a little more before your message will send:

Replace the placeholder credential values

Swap the placeholder values for account_sid and auth_token with your personal Twilio credentials. Go to https://www.twilio.com/console and log in. On this page, you’ll find your unique Account SID and Auth Token, which you’ll need any time you send messages through the Twilio Client like this. You can reveal your auth token by clicking on the eyeball icon:

Reveal Your Auth Token

 Open send_sms.py and replace the values for account_sid and auth_token  with your unique values.

Please note: it's okay to hardcode your credentials when getting started, but you should use environment variables to keep them secret before deploying to production. Check out how to set environment variables for more information.

Replace the _from phone number

Remember that SMS-enabled phone number you bought just a few minutes ago? Go ahead and replace the existing _from number with that one, making sure to use E.164 formatting:

[+][country code][phone number including area code]

Replace the _to phone number

Replace the _to phone number with your mobile phone number. This can be any phone number that can receive text messages, but it’s a good idea to test with your own phone so you can see the magic happen! As above, you should use E.164 formatting for this value.

Save your changes and run this script from your terminal:

python send_sms.py

That's it! In a few moments, you should receive an SMS from your Twilio number on your phone.

Are your customers in the U.S. or Canada? You can also send them MMS messages by adding just one line of code. Check out this guide to sending MMS to see how it's done.

If you are on a Twilio Trial account, your outgoing SMS messages are limited to phone numbers that you have verified with Twilio. Phone numbers can be verified via your Twilio Console's Verified Caller IDs.

Install Flask and Set Up Your Development Environment

In order to receive and reply to incoming SMS messages, we'll need to create a very lightweight web application that can accept incoming requests. We'll use Flask for this Quickstart, but if you prefer to use Django, you can find instructions in this blog post.

For instructions on setting up Flask on Windows, you can check out this handy guide.

Install Pip and Virtualenv

To install Flask and set up our development environment, we’ll need two tools: pip to install Flask and virtualenv to create a unique sandbox for this project. If you already have these tools installed, you can skip this section.

Pip comes pre-packaged with Python 3.4+, so if you’re on a recent version of Python, you don’t need to install anything new. If you’re on an earlier version, never fear: pip is included in virtualenv. So let’s install virtualenv!

If you’re using Python 2.4, run the following command in your terminal:

easy_install virtualenv

If you’re using Python 2.5-2.7, run the following command in your terminal, specifying your version number:

easy_install-2.7 virtualenv

Replace the 2.7 with 2.5 or 2.6 if you have that version installed.

To install virtualenv with Python 3.4+:

# If you get 'permission denied' errors try running "sudo python" instead of "python"
pip install virtualenv

If you get any errors in this step, check out these tips for debugging.

Create and Activate Your Virtual Environment

Once you have virtualenv installed, use your terminal to navigate to the directory you’re using for this Quickstart and create a virtual environment:

cd Documents/my_sms_quickstart_folder
virtualenv --no-site-packages .

Now, activate the virtual environment:

source bin/activate

You can verify that your virtualenv is running by looking at your terminal: you should see the name of the enclosing folder. It will look something like this:

(sms_quickstart)USER:~ user$

If you wish to point your virtual environment to a Python version that’s different from your default or just want to learn more about virtualenv, see this thorough guide.

Install Dependencies

Now we’re ready to install Flask. Create a file called requirements.txt and add the following lines to it:

Flask>=0.12
twilio~=6.0.0

Then install both of these packages with pip in your terminal:

bin/pip install -r requirements.txt

Test Everything from Scratch

First, make sure your virtualenv is activated:

cd Documents/my_tutorial_folder
source bin/activate     # On Windows, use .\bin\activate.bat

Then, create and open a file called run.py and add these lines:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run(debug=True)

Now it's time to try running it. In your terminal, type:

python run.py

You should see:

* Running on http://127.0.0.1:5000/

Navigate to http://localhost:5000 in your browser. You should see a "Hello World!" message. You’re ready to create your first Twilio messaging app!

If you encountered any issues or want instructions on setting up your environment with an older Python version (<3.4), check out our full guide to setting up a local Python dev environment.

Allow Twilio to Talk to Your Flask Application

We’re about to build a small Flask application to receive incoming messages. Before we do that, we need to make sure that Twilio can reach your application.

Most Twilio services use webhooks to communicate with your application. When Twilio receives an SMS, for example, it reaches out to a URL in your application for instructions on how to handle the message.

When you’re working on your Flask application in your development environment, your app is only reachable by other programs on your computer, so Twilio won’t be able to talk to it. We need to solve this problem by making your application accessible over the internet.

While there are a lot of ways to do this, like deploying your application to Heroku or AWS, you'll probably want a less laborious way to test your Twilio application. For a lightweight way to make your app available on the internet, we recommend a tool called Ngrok. Once started, Ngrok provides a unique URL on the ngrok.io domain which forwards incoming requests to your local development environment.

It works something like this:

How ngrok helps Twilio reach your local server

If you don’t already use Ngrok, head over to their download page and grab the appropriate binary for your operating system. Once downloaded, unzip the package.

If you're working on a Mac or Linux, you're all set. If you're on Windows, follow our guide on how to install and configure ngrok on Windows. For more info on ngrok, including some great tips and tricks, check out this in-depth blog post.

Once downloaded, start that Hello World application we made previously:

python run.py

Your local application must be running locally for Ngrok to do its magic.

Then open a new terminal tab or window and start Ngrok with this command:

./ngrok http 5000

If your local server is running on a different port, replace 5000 with the correct port number.

You should see output similar to this:

Ngrok server terminal output

Copy your public URL from this output and paste it into your browser. You should see your Flask application's "Hello, World!" message.

Receive and Reply to Inbound SMS Messages with Flask

When someone sends an SMS to your Twilio phone number, Twilio makes an HTTP request to your server asking for instructions on what to do next. Once you receive the request, you can tell Twilio to reply with an SMS, kick off a phone call, store details about the SMS in your database, or trigger something else entirely - it’s all up to you!

For this Quickstart, we’ll have our Flask app reply to incoming SMS messages with a thank you to the sender. Open up run.py again and update the code to look like this code sample:

Loading Code Samples...
Language
SDK Version:
  • 5.x
  • 6.x
# /usr/bin/env python
# Download the twilio-python library from twilio.com/docs/libraries/python
from flask import Flask, request, redirect
from twilio import twiml

app = Flask(__name__)

@app.route("/sms", methods=['GET', 'POST'])
def sms_ahoy_reply():
    """Respond to incoming messages with a friendly SMS."""
    # Start our response
    resp = twiml.Response()

    # Add a message
    resp.message("Ahoy! Thanks so much for your message.")

    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)
# /usr/bin/env python
# Download the twilio-python library from twilio.com/docs/libraries/python
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse

app = Flask(__name__)

@app.route("/sms", methods=['GET', 'POST'])
def sms_ahoy_reply():
    """Respond to incoming messages with a friendly SMS."""
    # Start our response
    resp = MessagingResponse()

    # Add a message
    resp.message("Ahoy! Thanks so much for your message.")

    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)
When your phone number receives an incoming message, Twilio will send an HTTP request to your server. This code shows how your server should respond to reply with a text message.
Reply to an incoming message using Twilio SMS

When your phone number receives an incoming message, Twilio will send an HTTP request to your server. This code shows how your server should respond to reply with a text message.

Save this file and restart your app with

python run.py

Double-check that Ngrok is still running on your localhost port. Now Twilio will be able to find your application - but first, we need to tell Twilio where to look.

Configure Your Webhook URL

For Twilio to know where to look, you need to configure your Twilio phone number to call your webhook URL whenever a new message comes in.

  1. Log into Twilio.com and go to the Console's Numbers page.
  2. Click on your SMS-enabled phone number.
  3. Find the Messaging section. The default “CONFIGURE WITH” is what you’ll need: "Webhooks/TwiML".
  4. In the “A MESSAGE COMES IN” section, select "Webhook" and paste in the URL you want to use.

Configure your SMS Webhook

Save your changes - you’re ready!

Test Your Application

As long as your localhost and the Ngrok servers are up and running, we’re ready for the fun part - testing our new Flask application!

Send a text message from your mobile phone to your Twilio phone number. You should see an HTTP request in your Ngrok console. Your Flask app will process the text message, and you’ll get your response back as an SMS.

Where to Next?

Now that you know the basics of sending and receiving SMS and MMS text messages with Python, you might want to check out these resources.

We can't wait to see what you build!

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
SDK Version:
  • 5.x
  • 6.x
# /usr/bin/env python
# Download the twilio-python library from twilio.com/docs/libraries/python
from twilio.rest import TwilioRestClient

# Find these values at https://twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"

client = TwilioRestClient(account_sid, auth_token)

client.messages.create(
    to="+12316851234",
    from_="+15555555555",
    body="Hello there!")
# /usr/bin/env python
# Download the twilio-python library from twilio.com/docs/libraries/python
from twilio.rest import Client

# Find these values at https://twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"

client = Client(account_sid, auth_token)

client.api.account.messages.create(
    to="+12316851234",
    from_="+15555555555",
    body="Hello there!")
SDK Version:
  • 5.x
  • 6.x
# /usr/bin/env python
# Download the twilio-python library from twilio.com/docs/libraries/python
from flask import Flask, request, redirect
from twilio import twiml

app = Flask(__name__)

@app.route("/sms", methods=['GET', 'POST'])
def sms_ahoy_reply():
    """Respond to incoming messages with a friendly SMS."""
    # Start our response
    resp = twiml.Response()

    # Add a message
    resp.message("Ahoy! Thanks so much for your message.")

    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)
# /usr/bin/env python
# Download the twilio-python library from twilio.com/docs/libraries/python
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse

app = Flask(__name__)

@app.route("/sms", methods=['GET', 'POST'])
def sms_ahoy_reply():
    """Respond to incoming messages with a friendly SMS."""
    # Start our response
    resp = MessagingResponse()

    # Add a message
    resp.message("Ahoy! Thanks so much for your message.")

    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)