Skip to content

Sending SMS with Twilio API

Setup overview

  • Create a Twilio account
  • Get Account SID + Auth Token
  • Buy/verify a sender phone number

Store secrets in env vars:

  • TWILIO_ACCOUNT_SIDTWILIO_ACCOUNT_SID
  • TWILIO_AUTH_TOKENTWILIO_AUTH_TOKEN

Example

twilio_sms.py
import os
 
# from twilio.rest import Client
 
 
def send_sms(to: str, body: str):
    account_sid = os.environ["TWILIO_ACCOUNT_SID"]
    auth_token = os.environ["TWILIO_AUTH_TOKEN"]
 
    # client = Client(account_sid, auth_token)
    # msg = client.messages.create(
    #     body=body,
    #     from_="+15551234567",
    #     to=to,
    # )
    # return msg.sid
 
 
# send_sms("+15550001111", "hello")
twilio_sms.py
import os
 
# from twilio.rest import Client
 
 
def send_sms(to: str, body: str):
    account_sid = os.environ["TWILIO_ACCOUNT_SID"]
    auth_token = os.environ["TWILIO_AUTH_TOKEN"]
 
    # client = Client(account_sid, auth_token)
    # msg = client.messages.create(
    #     body=body,
    #     from_="+15551234567",
    #     to=to,
    # )
    # return msg.sid
 
 
# send_sms("+15550001111", "hello")

Notes

  • keep rate limits in mind
  • never hardcode auth tokens

If this helped you, consider buying me a coffee β˜•

Buy me a coffee

Was this page helpful?

Let us know how we did