This tutorial builds a Flask web application with an HTML form that sends a Twilio SMS when a user submits a phone number and message, covering credential management, input validation, and error feedback. It targets developers who want to give non-technical team members a browser-based interface for sending text messages without direct API access. You will build a form with server-side validation, Twilio integration, flash message feedback, and basic protection against common misuse patterns.
Prerequisites and Setup
You need Python 3.7 or higher, Flask, Flask-WTF for CSRF protection, and the Twilio SDK, all installed with pip install twilio flask flask-wtf python-dotenv. Configure your Twilio credentials and a secret key for Flask sessions in a .env file; the secret key is required by Flask-WTF to generate CSRF tokens. Set WTF_CSRF_ENABLED=True in your Flask config and never disable it in production. Validate the submitted phone number on the server side before calling the Twilio API to prevent unnecessary API calls and give users clear error messages.
pip install twilio flask flask-wtf python-dotenv
# .env
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_PHONE_NUMBER=+15551234567
FLASK_SECRET_KEY=change-this-to-a-random-secret-string
The Complete Code
Flask-WTF's FlaskForm handles CSRF token generation and validation automatically, adding a hidden field to the form that Flask validates on every POST. The phone number field uses a simple regex validator to enforce E.164 format before the Twilio API is called. On a successful send, the route flashes a success message and redirects to avoid form resubmission on page refresh. On failure, the error from the Twilio exception is flashed back to the user so they understand what went wrong without seeing a raw stack trace.
import os
import re
from flask import Flask, render_template_string, flash, redirect, url_for, request
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, SubmitField
from wtforms.validators import DataRequired, Regexp
from twilio.rest import Client
from twilio.base.exceptions import TwilioRestException
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
app.config["SECRET_KEY"] = os.environ["FLASK_SECRET_KEY"]
app.config["WTF_CSRF_ENABLED"] = True
client = Client(os.environ["TWILIO_ACCOUNT_SID"], os.environ["TWILIO_AUTH_TOKEN"])
FROM = os.environ["TWILIO_PHONE_NUMBER"]
PHONE_RE = r"^+[1-9]d{7,14}$"
class SMSForm(FlaskForm):
phone = StringField("To (E.164 format)", validators=[
DataRequired(),
Regexp(PHONE_RE, message="Enter a valid E.164 phone number, e.g. +15551234567"),
])
message = TextAreaField("Message", validators=[DataRequired()])
submit = SubmitField("Send SMS")
TEMPLATE = """
<!DOCTYPE html>
<html><head><title>Send SMS</title></head><body>
<h2>Send an SMS via Twilio</h2>
{% for cat, msg in get_flashed_messages(with_categories=True) %}
<p style="color:{% if cat == 'error' %}red{% else %}green{% endif %}">{{ msg }}</p>
{% endfor %}
<form method="POST">
{{ form.hidden_tag() }}
<label>{{ form.phone.label }}</label><br>
{{ form.phone(size=20) }}<br>
{% if form.phone.errors %}
<span style="color:red">{{ form.phone.errors[0] }}</span><br>
{% endif %}
<label>{{ form.message.label }}</label><br>
{{ form.message(rows=4, cols=40) }}<br>
{{ form.submit() }}
</form>
</body></html>
"""
@app.route("/", methods=["GET", "POST"])
def index():
form = SMSForm()
if form.validate_on_submit():
try:
msg = client.messages.create(
body=form.message.data,
from_=FROM,
to=form.phone.data,
)
flash(f"Message sent successfully. SID: {msg.sid}", "success")
except TwilioRestException as e:
flash(f"Failed to send: {e.msg}", "error")
return redirect(url_for("index"))
return render_template_string(TEMPLATE, form=form)
if __name__ == "__main__":
app.run(port=5000, debug=True)
Testing and Debugging
Open a browser at http://localhost:5000, enter a valid E.164 number, type a short message, and click Send SMS. Verify the success flash message appears and the SMS arrives on the destination phone. Test validation by submitting without a phone number, with an invalid format like 5551234567 (missing the plus), and with an empty message field to verify the WTF validators reject each case with a clear error. On trial accounts, test with a verified number first; submitting an unverified number produces a Twilio error that should flash back as a user-readable message.
Taking It Further
Add authentication to the Flask app using Flask-Login so only authorized users can access the form, preventing unauthorized SMS sends that would consume your Twilio budget. Implement a per-user send rate limit using Flask-Limiter to cap how many messages any single session can send per hour. Log every send attempt to a database with the sender's session ID, destination number, message hash, timestamp, and resulting SID for audit and compliance purposes. Extend the form with a scheduled send option that uses the send_at parameter covered in the scheduling tutorial, giving users control over delivery timing from the same interface.
Get in touch with Telphi Consulting to build a secure internal SMS tool with user management, audit logging, and delivery tracking built in.
Ready to Transform Your Business Communications?
Get a free consultation with our VoIP experts and discover how we can help you save costs, improve efficiency, and scale your business.
Comments (0)
Join the discussion and share your thoughts (AI-moderated for quality)
Be the first to comment
No comments yet. Share your thoughts below.