Python 101: How to send SMS/MMS with Twilio

I’ve been hearing some buzz about a newish web service called Twilio which allows you to send SMS and MMS messages among other things. There’s a handy Python wrapper to their REST API as well. If you sign up with Twilio, they will give you a trial account without even requiring you to provide a credit card, which I appreciated. You will receive a Twilio number that you can use for sending out your messages. Since you are using a trail account, you do have to authorize any phone numbers you want to send messages to before you can actually send a message. Let’s spend some time learning how this works!


Getting Started

To get started, you’ll need to sign up on Twilio and you’ll also need to install the Python twilio wrapper. To install the latter, just do the following:

pip install twilio

Once that’s installed and you’re signed up, we’ll be ready to continue.


Using Twilio to Send SMS Messages

Sending an SMS (Short Message Service) message via Twilio is really easy. You will need to look in your Twilio account to get the sid and authentication token as well as your twilio number. Once you have those three pieces of key information, you can send an SMS message. Let’s see how:

from twilio.rest import TwilioRestClient


#----------------------------------------------------------------------
def send_sms(msg, to):
    """"""
    sid = "text-random"
    auth_token = "youAreAuthed"
    twilio_number = "123-456-7890"
    
    client = TwilioRestClient(sid, auth_token)
    
    message = client.messages.create(body=msg,
                                     from_=twilio_number,
                                     to=to,
                                     )

if __name__ == "__main__":
    msg = "Hello from Python!"
    to = "111-111-1111"
    send_sms(msg, to)

When you run the code above, you will receive a message on your phone that says the following: Sent from your Twilio trial account – Hello from Python!. As you can see, that was really easy. All you needed to do was create an instance of TwilioRestClient and then create a message. Twilio will do the rest. Sending an MMS (Multimedia Messaging Service) message is almost as easy. Let’s take a look at that in the next example!


Sending an MMS Message

Most of the time, you won’t actually want to put your sid, authentication token or Twilio phone number in the code itself. Instead, that would normall be stored in a database or config file. So in this example, we’ll put those pieces of information into a config file and extract them using ConfigObj. Here’s the contents of my config file:

[twilio]
sid = "random-text"
auth_token = "youAreAuthed!"
twilio_number = "123-456-7890"

Now let’s write some code to extract this information and send out an MMS message:

import configobj
from twilio.rest import TwilioRestClient


#----------------------------------------------------------------------
def send_mms(msg, to, img):
    """"""
    cfg = configobj.ConfigObj("/path/to/config.ini")
    sid = cfg["twilio"]["sid"]
    auth_token = cfg["twilio"]["auth_token"]
    twilio_number = cfg["twilio"]["twilio_number"]

    client = TwilioRestClient(sid, auth_token)
    
    message = client.messages.create(body=msg,
                                     from_=twilio_number,
                                     to=to,
                                     MediaUrl=img
                                     )

if __name__ == "__main__":
    msg = "Hello from Python!"
    to = "111-111-1111"
    img = "http://www.website.com/example.jpg"
    send_mms(msg, to=to, img=img)

This code generates the same message as the last one, but it also sends along an image. You will note that Trilio requires you to use either an HTTP or HTTPS URL to attach photos to your MMS message. Otherwise, that was pretty easy to do too!


Wrapping Up

What could you use this for in the real world? I’m sure businesses will want to use it to send out coupons or offer codes to new products. This also sounds like something that a band or politician would use to send out messages to their fans, consitutents, etc. I saw one article where someone used it to automate sending themselves sports scores. I found the service easy to use. I don’t know if their pricing is competitive, but the trial account is certainly good enough for testing and certainly worth a try.


Additional Reading

8 thoughts on “Python 101: How to send SMS/MMS with Twilio”

  1. The reason I ask is because I ran the MMS portion without any syntax changes, other than my own credentials and got KeyError: ‘twilio’. Also, what version of Python are you using?

  2. Oh, I see what the error is. The config file doesn’t show everything when rendered in the browser. Sorry about that. It’s fixed now. Also I tested with Python 2.7.6 on Kubuntu 14.04

  3. Oh, okay I see it. So it was a missing header in the config file. It worked after I added that. Thanks for the fix. I was testing in 3.4.1, so I thought maybe I was just borking some syntax. I was wondering where that twilio key was referenced.

    I used a simplified version to test that I got from the Twilio site. They have a handy code builder in there that’ll get you started:

    from twilio.rest import TwilioRestClient

    # put your own credentials here
    ACCOUNT_SID = “sid”
    AUTH_TOKEN = “token”

    client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)

    client.messages.create(

    to=”targetPhoneNumber”,

    from_=”twilioPhoneNumber”,

    body=”Testing this out from python!”,

    media_url=”https://i.imgur.com/xyz.jpg”,

    )

  4. Cool. I didn’t see the code builder. I was just playing around with the examples on their website. I’m surprised “media_url” worked for you. I think I tried that and got an error.

Comments are closed.