This guide demonstrates how to send a basic text message using the Twilio API. You’ll learn how to set up your environment, configure your API credentials, and send a text message.
twilio-sms-example.py
import osfrom dotenv import load_dotenvfrom twilio.rest import Client# Load environment variables from .env fileload_dotenv()# Get Twilio credentials and phone numbers from environment variablesaccount_sid = os.getenv('TWILIO_ACCOUNT_SID')auth_token = os.getenv('TWILIO_AUTH_TOKEN')phone_from = os.getenv('TWILIO_PHONE_FROM')phone_to = os.getenv('TWILIO_PHONE_TO')# Initialize Twilio client with account SID and auth tokenclient = Client(account_sid, auth_token)try:# Send a text message using Twilio API message = client.messages.create( body="Hello, World!", from_=phone_from, to=phone_to)# Print success responseprint(f"Message sent to {phone_to}. SID: {message.sid}")except Exception as e:# Print error responseprint(f"Failed to send message. Error: {e}")
You have successfully sent a text message using the Twilio API! This guide provided a basic example to get you started. You can now expand on this by customizing the message content and handling different phone numbers.