Send SMS updates to mobile phone using python

In this tutorial, we are going to learn how to send SMS messages in Python using the Twilio API service. Twilio provides a simple and reliable way to send SMS messages programmatically.

Setting Up Twilio Account

First, go to Twilio and create an account. You will get a free trial account with some credits to test SMS functionality. Complete the account setup and verify your phone number.

Installation

Install the twilio module using pip ?

pip install twilio

Getting Twilio Credentials

From your Twilio Console Dashboard, you need to collect ?

  • Account SID − Your unique account identifier
  • Auth Token − Your authentication token
  • Twilio Phone Number − The phone number provided by Twilio

Sending SMS Example

Here's a complete example to send an SMS message ?

from twilio.rest import Client

# Your Account Sid and Auth Token from twilio account
account_sid = 'your_account_sid_here'
auth_token = 'your_auth_token_here'

# Instantiating the Client
client = Client(account_sid, auth_token)

# Sending message
message = client.messages.create(
    body='Hi there! How are you?',
    from_='+1234567890',  # Your Twilio phone number
    to='+0987654321'      # Verified recipient number
)

# Printing the message SID after success
print(f"Message sent successfully! SID: {message.sid}")

If the message is sent successfully, you will get a unique message SID (identifier) ?

Message sent successfully! SID: SMd954e170ca2545248075c3bc2623aabd

Important Notes

  • Phone Number Format − Use international format with country code (e.g., +1234567890)
  • Trial Account Limitations − You can only send messages to verified phone numbers
  • Security − Never hardcode credentials in production; use environment variables

Error Handling

Add error handling to make your SMS sending more robust ?

from twilio.rest import Client
from twilio.base.exceptions import TwilioRestException

try:
    account_sid = 'your_account_sid_here'
    auth_token = 'your_auth_token_here'
    
    client = Client(account_sid, auth_token)
    
    message = client.messages.create(
        body='Hello from Python!',
        from_='+1234567890',
        to='+0987654321'
    )
    
    print(f"SMS sent successfully! SID: {message.sid}")
    
except TwilioRestException as e:
    print(f"Error sending SMS: {e}")

Conclusion

Twilio makes it easy to send SMS messages from Python applications. Remember to keep your credentials secure and handle errors gracefully. With a few lines of code, you can integrate SMS functionality into any Python project.

Updated on: 2026-03-25T09:02:03+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements