This tutorial shows how to send SMS to a list of recipients using the Twilio Python SDK with per-message error handling and rate limiting so you do not hit API throttle limits. It targets developers sending appointment reminders, alerts, or notifications to multiple users at once. You will build a script that reads recipients from a list, sends each message, tracks results, and logs failures without stopping the entire batch.
Prerequisites and Setup
You need Python 3.7 or higher, the Twilio SDK installed, and your credentials loaded from a .env file as shown in the first-SMS tutorial. Run pip install twilio python-dotenv if you have not done so already. Prepare your recipients as a Python list of dicts containing at minimum a phone field in E.164 format; you can load these from a CSV with the built-in csv module. Twilio's free tier caps outbound SMS at one message per second per account, so a time.sleep(1) between sends keeps you inside the limit.
pip install twilio python-dotenv
# recipients.csv
phone,name
+15551234567,Alice
+15559876543,Bob
+15554443322,Charlie
The Complete Code
The script loads recipients from a CSV, iterates through them inside a try/except block, and records the outcome of each send in a results list. Catching TwilioRestException per iteration means one bad number does not abort the rest of the batch. The time.sleep(1) call after each send respects Twilio's rate limit at the default account tier. Printing a summary at the end gives you an immediate success and failure count without checking the Console manually.
import os
import csv
import time
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"])
FROM = os.environ["TWILIO_PHONE_NUMBER"]
results = {"sent": [], "failed": []}
with open("recipients.csv", newline="") as f:
for row in csv.DictReader(f):
try:
msg = client.messages.create(
body=f"Hi {row['name']}, this is a message from Telphi.",
from_=FROM,
to=row["phone"],
)
results["sent"].append({"phone": row["phone"], "sid": msg.sid})
except TwilioRestException as e:
results["failed"].append({"phone": row["phone"], "error": str(e)})
time.sleep(1)
print(f"Sent: {len(results['sent'])} Failed: {len(results['failed'])}")
for fail in results["failed"]:
print(f" FAILED {fail['phone']}: {fail['error']}")
Testing and Debugging
Start with a CSV containing only two or three verified numbers to confirm the loop and error handling work before scaling up. If several messages fail with error code 21614, those numbers are landlines that cannot receive SMS; add a pre-send Lookup API check to filter them out. Check the Twilio Console under Messaging Logs to compare the SIDs in your results list against what Twilio received. If you need to send at higher throughput, upgrade your Twilio account tier, which increases the rate limit, and consider using a Messaging Service with a sender pool.
Taking It Further
Replace the flat Python list with a database query so recipients are pulled from your production data store each time the script runs. Add a status_callback URL to every create() call so delivery receipts are stored per-recipient for reporting. Use Python's concurrent.futures.ThreadPoolExecutor with a bounded semaphore to parallelize sends within your rate limit. For very large lists, consider Twilio Notify or a Messaging Service with long code pools to distribute send volume across multiple numbers.
Contact Telphi Consulting for guidance on building high-volume SMS pipelines that meet carrier compliance requirements.
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.