How to send an SMS in Python

1 min

To send an SMS in Python, you can use a third-party SMS API, such as Twilio or Vonage. These APIs provide libraries for Python that allow you to interact with their SMS platform programmatically.

Here's an example of how to send an SMS using Twilio:

from twilio.rest import Client

# Your Account SID and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

message = client.messages \
                .create(
                     body="Hello from Python!",
                     from_='+12345678901',
                     to='+12345678902'
                 )

print(message.sid)

In the code above, you first need to install the Twilio library by running pip install twilio. Then, you need to create an account with Twilio and obtain your account_sid and auth_token from the Twilio console.

Finally, you create a Client object and use it to send an SMS with the body text "Hello from Python!", the sender phone number from_, and the recipient phone number to.

The exact details of how to send an SMS will vary depending on the API you choose. Be sure to check the documentation for the API you're using for more information.