Twilio is a cloud communications platform that allows developers to send and receive messages via SMS. Integrating Twilio’s API for SMS notifications can enhance your application’s functionality, providing timely updates to users. Below are practical examples to help you get started.
Before you begin, ensure you have the following:
This example demonstrates how to send a simple SMS message using Python.
## Import the Twilio Client from the Twilio library
from twilio.rest import Client
## Your Twilio Account SID and Auth Token
account_sid = 'your_account_sid'
auth_token = 'your_auth_token'
## Initialize the Twilio client
client = Client(account_sid, auth_token)
## Send an SMS
message = client.messages.create(
body='Hello from Twilio!',
from_='+1234567890', # Your Twilio number
to='+0987654321' # Recipient's number
)
## Print the message SID
print(f'Message SID: {message.sid}')
Client class from the Twilio library is imported to facilitate sending messages.'your_account_sid' and 'your_auth_token' with your actual Twilio credentials.messages.create() method sends the SMS, specifying the message body, sender’s number, and recipient’s number.In this example, we’ll send an SMS notification when a user signs up for your service.
def send_signup_notification(user_phone):
# # Initialize the Twilio client
client = Client(account_sid, auth_token)
# # Prepare the message
message = client.messages.create(
body='Welcome to our service! Thank you for signing up.',
from_='+1234567890', # Your Twilio number
to=user_phone # User's phone number
)
# # Print confirmation
print(f'Notification sent to {user_phone} with SID: {message.sid}')
## Example usage
send_signup_notification('+0987654321')
send_signup_notification function takes a user’s phone number as an argument.It’s essential to handle potential errors when sending SMS notifications. Below is an example of how to manage exceptions.
try:
client.messages.create(
body='This is a test message.',
from_='+1234567890', # Your Twilio number
to='+0987654321' # Recipient's number
)
except Exception as e:
print(f'Failed to send message: {e}')
create() method in a try-except block allows you to catch any exceptions, such as invalid phone numbers or connectivity issues.Integrating the Twilio API for SMS notifications is straightforward with clear examples. By following these examples, you can enhance your application with effective communication capabilities. For further customization and features, refer to the Twilio API documentation.