This tutorial shows how to schedule SMS messages for future delivery using Twilio's MessageScheduling feature in PHP. It targets developers who need to send appointment reminders, payment alerts, or marketing messages at a precise future time without running a cron job or background process per message. You will use the sendAt and scheduleType options together with a Twilio Messaging Service SID to queue a message and optionally cancel it before it sends.
Prerequisites and Setup
Install the packages with composer require twilio/sdk vlucas/phpdotenv and create a Messaging Service in the Twilio Console under Messaging, Services, then enable Message Scheduling in that service's feature settings. Copy the Messaging Service SID, which starts with MG, and add it to your .env file. Scheduled messages require a Messaging Service SID as the sender instead of a direct from number because Twilio's scheduling infrastructure runs through the Messaging Service layer. The sendAt value must be a UTC timestamp in ISO 8601 format between 15 minutes and 7 days from the current time.
composer require twilio/sdk vlucas/phpdotenv
# .env
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_MESSAGING_SERVICE_SID=MGxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
The Complete Code
PHP's DateTime class with a UTC timezone generates the correct timestamp; add the desired offset using DateInterval and format it with 'Y-m-dTH:i:sZ' to produce the required ISO 8601 UTC string. The scheduleType option must be the string 'fixed' to activate scheduling; omitting it causes Twilio to ignore sendAt and deliver immediately. The returned message object has a status of scheduled and a SID you can use to cancel the message before the send time arrives. Cancellation is done by fetching the message by SID and calling its update() method with status set to 'canceled'.
<?php
require_once 'vendor/autoload.php';
use TwilioRestClient;
use TwilioExceptionsRestException;
$dotenv = DotenvDotenv::createImmutable(__DIR__);
$dotenv->load();
$client = new Client($_ENV['TWILIO_ACCOUNT_SID'], $_ENV['TWILIO_AUTH_TOKEN']);
$messagingService = $_ENV['TWILIO_MESSAGING_SERVICE_SID'];
function scheduleSms(Client $client, string $msid, string $to, string $body, int $minutesFromNow): ?string {
$sendAt = new DateTime('now', new DateTimeZone('UTC'));
$sendAt->add(new DateInterval('PT' . $minutesFromNow . 'M'));
$sendAtStr = $sendAt->format('Y-m-dTH:i:sZ');
try {
$message = $client->messages->create($to, [
'messagingServiceSid' => $msid,
'body' => $body,
'sendAt' => $sendAtStr,
'scheduleType' => 'fixed',
]);
echo 'Scheduled SID: ' . $message->sid . ' Status: ' . $message->status . PHP_EOL;
return $message->sid;
} catch (RestException $e) {
echo 'Error ' . $e->getStatusCode() . ': ' . $e->getMessage() . PHP_EOL;
return null;
}
}
function cancelScheduled(Client $client, string $sid): bool {
try {
$client->messages($sid)->update(['status' => 'canceled']);
echo 'Cancelled: ' . $sid . PHP_EOL;
return true;
} catch (RestException $e) {
echo 'Cancel error: ' . $e->getMessage() . PHP_EOL;
return false;
}
}
$sid = scheduleSms($client, $messagingService, '+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 a RestException with status code 21705, your Messaging Service does not have scheduling enabled; open the service settings in the Console and toggle on Message Scheduling. Error code 21706 means your sendAt timestamp is less than 15 minutes from now or more than 7 days ahead; adjust the interval and retry. Test the cancellation function before the send time and refresh the Console to confirm the message status changes to canceled.
Taking It Further
Accept a DateTimeImmutable object as the parameter instead of a minutes offset so callers can pass any arbitrary future time expressed in any timezone and the function handles the UTC conversion internally. Store each scheduled message SID in a database row alongside the recipient, body, and intended send time so you can cancel or reschedule messages from a management UI. Build a Laravel appointment reminder command that queries upcoming bookings, schedules two messages per booking (24 hours before and 1 hour before), and stores both SIDs for cancellation if the booking is rescheduled. For high-volume scheduling, add a sleep between create calls and respect the Twilio API rate limits to avoid 429 throttle responses.
Contact Telphi Consulting to build an automated scheduled messaging system integrated with your PHP or Laravel booking platform.
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.