Back to Blog
Language How-Tos

How to Set Up a Voicemail System in Twilio Using Python

Build a full voicemail system in Python with Twilio that records messages when calls go unanswered and sends email or SMS notifications.

DA
Danial A
Senior Twilio Consultant, Telphi Consulting
June 22, 2026
8 min read
Twilio
Python
How-To
Code
How to Set Up a Voicemail System in Twilio Using Python

This tutorial builds a complete voicemail system using Flask, Twilio TwiML, and Python that records messages from callers when no one answers and sends an SMS notification to the team with details about the new voicemail. It targets developers who need a programmable voicemail solution with transcription and notification support. You will build a TwiML flow that greets callers, records their message, stores the recording details, and fires an SMS notification to a designated number.

Prerequisites and Setup

You need Python 3.7 or higher, Flask, and the Twilio SDK installed with pip install twilio flask python-dotenv. The voicemail system uses two Flask routes: one that returns the TwiML greeting and Record verb, and one that receives the recording callback after Twilio has processed the audio. Configure your Twilio number's voice webhook to POST to your greeting route so every unanswered call is directed to the voicemail flow. Store the notification recipient's phone number as an environment variable separate from your Twilio number.

pip install twilio flask python-dotenv

# .env
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_PHONE_NUMBER=+15551234567
NOTIFICATION_NUMBER=+15559998888

The Complete Code

The greeting route plays a professional greeting using the Say verb and then activates the Record verb with a maximum duration of 120 seconds and transcription enabled. Twilio records the audio, processes it, and then POSTs the recording details to the action URL specified on the Record verb. The recording action route receives the caller's number, recording URL, duration, and transcript URL, and immediately sends an SMS notification to the team. The Twilio client in the notification handler is the same client used for outbound SMS, making it straightforward to add multiple notification methods.

import os
from flask import Flask, request
from twilio.rest import Client
from twilio.twiml.voice_response import VoiceResponse
from twilio.base.exceptions import TwilioRestException
from dotenv import load_dotenv

load_dotenv()

app    = Flask(__name__)
client = Client(os.environ["TWILIO_ACCOUNT_SID"], os.environ["TWILIO_AUTH_TOKEN"])
FROM   = os.environ["TWILIO_PHONE_NUMBER"]
NOTIFY = os.environ["NOTIFICATION_NUMBER"]

@app.route("/voicemail/greeting", methods=["POST"])
def voicemail_greeting():
    resp = VoiceResponse()
    resp.say(
        "You have reached Telphi Consulting. "
        "We are unable to take your call right now. "
        "Please leave your name, number, and a brief message after the tone, "
        "and we will return your call within one business day.",
        voice="alice",
    )
    resp.record(
        timeout=5,
        max_length=120,
        transcribe=True,
        action="/voicemail/recorded",
        method="POST",
        finish_on_key="#",
        play_beep=True,
    )
    resp.say("We did not receive a message. Goodbye.", voice="alice")
    return str(resp), 200, {"Content-Type": "text/xml"}

@app.route("/voicemail/recorded", methods=["POST"])
def voicemail_recorded():
    caller   = request.form.get("Caller", "Unknown")
    duration = request.form.get("RecordingDuration", "0")
    rec_url  = request.form.get("RecordingUrl", "")
    rec_sid  = request.form.get("RecordingSid", "")

    print(f"New voicemail from {caller} ({duration}s) SID: {rec_sid}")

    try:
        client.messages.create(
            body=(
                f"New voicemail from {caller} ({duration}s). "
                f"Recording SID: {rec_sid}. "
                f"Check the Twilio Console or your recordings dashboard to listen."
            ),
            from_=FROM,
            to=NOTIFY,
        )
    except TwilioRestException as e:
        print(f"Notification failed: {e.msg}")

    resp = VoiceResponse()
    resp.say("Your message has been recorded. Thank you and goodbye.", voice="alice")
    return str(resp), 200, {"Content-Type": "text/xml"}

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

Testing and Debugging

Call your Twilio number, listen for the greeting, leave a 10-second test message, and press # or hang up. Within 30 seconds you should receive the SMS notification with the recording SID. Check the Flask terminal for the voicemail_recorded POST to confirm Twilio called the action URL with the recording details. If the recording notification arrives but the SMS does not send, check the Flask terminal for a TwilioRestException and verify your notification number is verified under Verified Caller IDs if you are on a trial account.

Taking It Further

Store each voicemail's recording SID, caller, duration, and timestamp in a database and build a simple web dashboard that lists new voicemails and links to their audio files. Add a transcribe_callback attribute to the Record verb pointing to a separate route that receives and stores the transcription text alongside the recording record. Send email notifications instead of or in addition to SMS using Python's smtplib or a transactional email service with the recording URL and transcript in the email body. Set up a cron job that downloads recording MP3 files to S3 and then deletes them from Twilio to avoid storage charges after a configurable retention period.

Contact Telphi Consulting to build a production voicemail management system with transcription, email notifications, and a web playback interface.

Share this article:
0 views

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)

Protected by AI moderation

Be the first to comment

No comments yet. Share your thoughts below.