In this tutorial, you will learn how to send an SMS using Twilio API.
In my last post, I showed you how to send e-mails using python. This time I will show you how you can send an SMS without any hardware. In the following video, you can see how to create an account in Twilio and then send an SMS using python.
Creating an Account
Access to the Twilio site and click on the “Sign up” button. A window like the following image (Figure 1) will appear. There you should put your personal information. You will receive on your email a confirmation link; click on it.
A new tab on your browser will be opened asking for a phone number (Figure 2). After inserting your phone number there, you will receive a code that will be used to verify the number as yours.
You want to send an SMS, to do this, you will need a Twilio phone number. With the trial account, you can get one free USA or Canada number with $15,50 to spend.
To obtain a number, click on the Dashboard button saying “Get a trial phone number” (Figure 3).
Send a message
To send a message, firstly access the “Programmable Messaging Dashboard” tab, and then click on the “Try it Out” option (Figure 4).
Figure 5 is what you will get. Click on the “Start setup” button. Then name your messaging service and provide a Twilio number to the service (the one you previously created).
Now that the setup is done click on the “Try SMS” option. After filling the text boxes, it will be outputted the code that you will use to send SMS in diverse languages like curl, Java, Ruby, PHP, Python, C#, and Node.js. You can check the result of this tutorial using the python code in the video on the top of this page.
Here is the python code outputted by Twilio API that can be implemented in your project to send text messages.
Each time you run this code will be sent one text message from your Twilio number to the receptor. You can append this code to your project or turn it into a function making this one of the simplest and intuitive ways of sending messages that I know.
Don’t name your file as “twilio.py” and don’t forget to install the Twilio package to run the code successfully. To install it, you can use the following command: pip install twilio.
from twilio.rest import Client account_sid = '[Account SID]' # Your account ID auth_token = '[AuthToken]' # Authentication token, you can hide this in other file client = Client(account_sid, auth_token) message = client.messages.create( messaging_service_sid='[Service SID]', # SID of the service you created body='[Body]', # The body of your message to='[To number]' # Number of who you want to send a mensage ) print(message.sid)