Today, almost everyone uses SMS. Text messages give you a simple, convenient way to chat with friends, get important updates, and handle basic security tasks like 2FA. If you’re a developer, Python offers similar simplicity and convenience, making it one of the world’s most popular programming languages.
So why not bring these two methods together and use Python to send SMS messages?
In this tutorial, we will show you how to send an SMS using Python and Flask. We’ve prepared a small code sample which will be an excellent starting point for creating your application.
Vonage API Account
To create your Python SMS app, you will need a Vonage API account. To be able to use the Vonage Messages API, you'll have to create a Vonage Application from the developer portal.
Open API Settings. Under the API keys tab, you will find your API key and Account secret (API secret). We will use these credentials later.
Install the Vonage Python SDK
First, make sure that your laptop/server has Python 3 installed. We will then use venv to create an isolated environment with only the necessary packages.
Install virtualenv
via pip.
Create the virtual environment
Activate your virtual environment
Install the Vonage Python SDK
Run REPL, the Python language shell
Import the Vonage Python SDK
Create a Vonage Client object that can be re-used and knows your Vonage API key and its secret.
Use send_message method
to send an SMS. You can replace "Vonage APIs" with related Sender ID (SMS sender name)
Expected output
We receive a dictionary where we can parse the following information: Was the message sent successfully? The "status': '0" means that all is good. How many messages was your SMS divided into? How much does it cost you to send the message? It depends on the number of symbols in the SMS and the receiver’s country.
Check your phone notification, and you should receive an SMS message. If not, check the contents of the response.
You can monitor and troubleshoot SMS delivery on the Vonage API Dashboard
Create an SMS Sender with Python and Flask
Let's create a tiny web application using Flask and Python to send an SMS. Our app should contain a form for a phone number and an SMS message. When users press "Send SMS," it will post to a second view that will send the SMS using the Vonage SMS API. Create a server.py file and paste related code there.
from dotenv import load_dotenv
from flask import Flask, flash, redirect, render_template, request, url_for
import vonage
from os import environ as env
# Load environment variables from a .env file:
load_dotenv('.env')
# Load in configuration from environment variables:
VONAGE_API_KEY = env['VONAGE_API_KEY']
VONAGE_API_SECRET = env['VONAGE_API_SECRET']
VONAGE_NUMBER = env['VONAGE_NUMBER']
# Create a new Vonage Client object:
client = vonage.Client(
key=VONAGE_API_KEY, secret=VONAGE_API_SECRET
)
# Initialize Flask:
app = Flask(__name__)
app.config['SECRET_KEY'] = env['FLASK_SECRET_KEY']
@app.route('/')
def index():
""" A view that renders the Send SMS form. """
return render_template('index.html')
@app.route('/send_sms', methods=['POST'])
def send_sms():
""" A POST endpoint that sends an SMS. """
# Extract the form values:
to_number = request.form['to_number']
message = request.form['message']
# Send the SMS message:
result = client.sms.send_message({
'from': VONAGE_NUMBER,
'to': to_number,
'text': message,
})
# Redirect the user back to the form:
return redirect(url_for('index'))
Let's now create a template at templates/index.html
The following HTML includes the Bootstrap CSS framework and then renders a form with two fields: to_number
for taking the destination phone number and message
, so the user can enter their SMS message.
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Send an SMS</title>
<script src="https://code.jquery.com/jquery-3.5.0.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.14.7/dist/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<div class="container">
<h1>Send an SMS</h1>
<form action="/send_sms" method="POST">
<div class="form-group"><label for="destination">Phone Number</label>
<input id="to_number" class="form-control" name="to_number" type="tel" placeholder="Phone Number"></div>
<div class="form-group"><label for="message">Message</label>
<textarea id="message" class="form-control" name="message" placeholder="Your message goes here"></textarea></div>
<button type="submit" class="btn btn-primary">Send SMS</button>
</form>
</div>
In this tutorial, we will use the python-dotenv library to load a .env
file. Before starting your server, you'll need to provide a configuration in a .env
file. Start with the following and fill in your details:
Create requirements.txt
and put related dependencies as in this file
Start your app with the following command
Open http://localhost:5000/ in your browser and navigate to the “Send an SMS Using the Python Application” chapter.
Deploy From Code Source
Alternatively, you can deploy an application using a prepared code sample. To deploy the application, you need to clone the repo using git and update .env
with your credentials
Clone the source code.
Go to the project folder.
Install the dependencies.
Start your app with the following command.
Expected output:
Next, open http://localhost:5000/ in your browser and you should see the following web page
Send an SMS Using the Python Application
Let's send an SMS using this interface. Ensure the number is in international format without the '+' at the start. Hit "Send SMS" and check your phone! You can find the source code of this application here.
Wrap-up
Congratulations! You've now built an application to send an SMS. You can also use the Vonage Messages API to send messages with Viber Business Messages, Facebook Messenger, and WhatsApp.
Let us know how we can help! Join the conversation on our Vonage Community Slack or send us a message on Twitter.