Back to Blog
Language How-Tos

How to Schedule SMS Messages in Twilio Using Python

Schedule future SMS delivery in Twilio using Python with the MessageSchedule parameter and handle scheduled message cancellation.

DA
Danial A
Senior Twilio Consultant, Telphi Consulting
June 22, 2026
8 min read
Twilio
Python
How-To
Code
How to Schedule SMS Messages in Twilio Using Python

This tutorial shows how to schedule SMS messages for future delivery using Twilio's MessageScheduling feature in Python. It targets developers who need to send appointment reminders, payment alerts, or marketing messages at a specific future time without running a background job or cron task. You will use the send_at and schedule_type parameters together with a Twilio Messaging Service to queue a message and optionally cancel it before it sends.

Prerequisites and Setup

You need Python 3.7 or higher, the Twilio SDK installed, and a Messaging Service with scheduling enabled in the Twilio Console. Install dependencies with pip install twilio python-dotenv and copy your Messaging Service SID (starts with MG) from the Console. Scheduled messages require a Messaging Service SID instead of a direct from_ number, because Twilio uses the service's sender pool and scheduling infrastructure. The send_at value must be a UTC datetime between 15 minutes and 7 days in the future, formatted as an ISO 8601 string.

pip install twilio python-dotenv

# .env
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_MESSAGING_SERVICE_SID=MGxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

The Complete Code

Python's datetime module with UTC timezone awareness generates the correct send_at timestamp; always use timezone-aware datetimes to avoid conversion bugs. The schedule_type parameter must be set to the string "fixed" to activate scheduling. Twilio returns the message SID immediately, and the message enters a scheduled status until the send_at time arrives. You can cancel a scheduled message before it sends by calling client.messages(sid).update(status="canceled").

import os
from datetime import datetime, timezone, timedelta
from twilio.rest import Client
from twilio.base.exceptions import TwilioRestException
from dotenv import load_dotenv

load_dotenv()

client = Client(os.environ["TWILIO_ACCOUNT_SID"], os.environ["TWILIO_AUTH_TOKEN"])
MESSAGING_SERVICE_SID = os.environ["TWILIO_MESSAGING_SERVICE_SID"]

def schedule_sms(to: str, body: str, minutes_from_now: int) -> str:
    send_at = datetime.now(timezone.utc) + timedelta(minutes=minutes_from_now)
    try:
        message = client.messages.create(
            to=to,
            body=body,
            messaging_service_sid=MESSAGING_SERVICE_SID,
            send_at=send_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
            schedule_type="fixed",
        )
        print(f"Scheduled SID: {message.sid}  Status: {message.status}")
        return message.sid
    except TwilioRestException as e:
        print(f"Schedule error {e.code}: {e.msg}")
        return ""

def cancel_scheduled_sms(sid: str) -> bool:
    try:
        client.messages(sid).update(status="canceled")
        print(f"Cancelled message {sid}")
        return True
    except TwilioRestException as e:
        print(f"Cancel error {e.code}: {e.msg}")
        return False

sid = schedule_sms("+15551234567", "Your appointment is in 1 hour.", 30)

Testing and Debugging

Schedule a message 20 minutes in the future and check the Twilio Console under Messaging Logs where the status shows as scheduled. If you receive error code 21705, your Messaging Service does not have scheduling enabled; go to the Twilio Console, open the service settings, and turn on Message Scheduling. Error code 21706 means your send_at time is less than 15 minutes from now or more than 7 days ahead, so adjust the offset. Use the cancellation function before the send time and refresh the Console to verify the status changes to canceled.

Taking It Further

Build a scheduling wrapper that accepts a Python datetime object in any timezone and converts it to UTC automatically using pytz or zoneinfo before passing it to the API. Store each scheduled message's SID in a database alongside the recipient, content, and intended send time so you can look up and cancel messages from a management interface. Implement a pre-send reminder system where you schedule two messages: one day before and one hour before an appointment, and cancel both if the appointment is rescheduled. For large-scale scheduling, batch your schedule_sms calls and add rate limiting to stay within Twilio's API request limits.

Contact Telphi Consulting to build a fully automated scheduled messaging system integrated with your CRM or booking platform.

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.