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. Prefer to use Django? Check out this blog post.
In this Quickstart, you will learn how to:
- Sign up for Twilio and get your first SMS-enabled Twilio phone number
- Set up your development environment to send and receive messages
- Send your first SMS
- Receive inbound text messages
- Reply to incoming messages with an SMS
Prefer to get started by watching a video? Check out our Python SMS Quickstart video on Youtube.
Already have a Twilio account? Go ahead and skip this section.
You can sign up for a free Twilio trial account here.
- When you sign up, you'll be asked to verify your personal phone number. This helps Twilio verify your identity and also allows you to send test messages to your phone from your Twilio account while in trial mode.
- Once you verify your number, you'll be asked to create a project. For the sake of this tutorial, you can click on the "Learn and Explore" template. Give your project a name, or just click "skip remaining steps" to continue with the default.
- Once you get through the project creation flow, you'll arrive at your project dashboard in the Twilio Console. This is where you'll be able to access your Account SID an authentication token, find a Twilio phone number, and more.
Install the Twilio CLI
We'll need to use the Twilio CLI (command line interface) for a few tasks, so let's install that next.
One of the easiest ways to install the CLI on Mac OS X is to use Homebrew. If you don't already have it installed, visit the Homebrew site for installation instructions and then return here.
Once Homebrew is installed, simply run the following command to install the CLI:
brew tap twilio/brew && brew install twilio
Updating
If you already installed the CLI with brew and want to upgrade to the latest version, run:
brew upgrade twilio
Before we can install, we need to make sure you have Node.js installed (version 8 or above). To see if you have node installed, try running this command:
node -v
If your system reports v8.0.0 or above, you can skip the next step.
Installing Node.js on Windows
Using the Windows Installer (.msi) is the recommended way to install Node.js on Windows. You can download the installer from the Node.js download page.
Installing Twilio CLI
The CLI is installed with npm (Node Package Manager), which comes with Node.js. To install the CLI run the following command:
npm install twilio-cli -g
Note the -g option is what installs the command globally so you can run it from anywhere in your system.
Updating
If you already installed the CLI with npm and want to upgrade to the latest version, run:
npm install twilio-cli@latest -g
Before we can install, we need to make sure you have Node.js installed (version 8 or above). Even if you already installed Node yourself, the CLI works best when you install it using nvm. Here's how to get nvm installed on most Linux systems:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
Please visit the nvm installation instructions for additional options and troubleshooting steps. Once you have nvm installed, run the following to install and use the most recent LTS release of Node.js:
nvm install --lts nvm use <insert version reported from above>
Installing other Twilio CLI prerequisites for Linux
Depending on your distribution, you will need to run one of the following commands:
- Debian/Ubuntu:
sudo apt-get install libsecret-1-dev
- Red Hat-based:
sudo yum install libsecret-devel
- Arch Linux:
sudo pacman -S libsecret
Installing Twilio CLI
The CLI is installed with npm (Node Package Manager), which comes with Node.js. To install the CLI run the following command:
npm install twilio-cli -g
Note the -g option is what installs the command globally so you can run it from anywhere in your system.
Updating
If you already installed the CLI with npm and want to upgrade to the latest version, run:
npm install twilio-cli@latest -g
Run twilio login
to get the Twilio CLI connected to your account. Visit https://www.twilio.com/console, and you’ll find your unique Account SID and Auth Token to provide to the CLI.
You can reveal your auth token by clicking on the eyeball icon:
Get a phone number
If you don't currently own a Twilio phone number with SMS functionality, you'll need to purchase one. With the CLI, run:
twilio phone-numbers:buy:local --country-code US --sms-enabled
Replace US with your ISO-3166-1 country code if you would like a phone number in another country. If you aren't finding any SMS enabled numbers, try looking for a mobile number instead of a local number: twilio phone-numbers:buy:mobile --country-code DE --sms-enabled
Select a phone number to add it to your account.
Next, we need to install Python and the Twilio Python 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, or follow the instructions from Python's documentation.
Twilio’s Python server-side 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 Server-side SDK
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 server-side SDK library code.
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.
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 'view' link:
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.
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.
When you send an SMS from your free trial phone number, it will always begin with "Sent from a Twilio trial account." We remove this message after you upgrade.
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.
Receive and reply to inbound SMS messages with Python
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. For this Quickstart, we’ll reply to the sender with a note about how we're sending our SMS reply.
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 # On Windows, use .\Scripts\activate.bat
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_sms_quickstart_folder source bin/activate # On Windows, use .\Scripts\activate.bat
Then, create and open a file called run.py
and add the code from this example:
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/sms in your browser. You should see an "Ahoy!" 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.
Configure your Webhook URL
Now, you need to configure your Twilio phone number to call your webhook URL whenever a new message comes in. Just run this CLI command, replacing the phone number with your Twilio phone number:
twilio phone-numbers:update "+15017122661" --sms-url="http://localhost:5000/sms"
The CLI will start an ngrok tunnel (so Twilio can reach your development machine) and wait patiently for incoming text messages!
Test your application with a text
Now that everything is glued together, it's time to test.
Send a text message from your mobile phone to your Twilio phone number. You'll see a couple of things happen very quickly -
- Your Flask app will note a new connection
- Twilio will forward 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.
- Dive into the API Reference documentation for Twilio SMS
- Learn how to create an SMS conversation in Python
- Track the delivery status of your messages with Python
- Send an SMS during a phone call
- Learn how to build cool things with TwilioQuest, our interactive, self-paced game that teaches you how to Twilio.
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.