Sending SMS Text Messages Using Python

For one of my Pi projects I wanted the ability to send SMS text messages from a Python script. These messages would be sent to my mobile phone and alert me about specific events recorded by my Pi. There was no possibility of connecting the Pi to a mobile phone so I decided to send the SMS via the internet.

In previous years there were services that allowed you to send free text messages via the Internet. In general these services were either illegal or relied on loopholes in mobile phone networks that have since been fixed.

So the only reliable solution is to use an SMS Gateway.

TxtLocal LogoSending messages via a legitimate gateway costs per message but this cost is low (approximately 5p per message) and you know the service will be available and reliable.

I decided to use TxtLocal as they provided a low cost solution with the added bonus of example Python code to send messages from within a script. They provide full documentation on their SMS API Gateway page which includes code examples for PHP, ASP, C#, VB .Net, VBA, Java and Perl as well as Python. This was perfect for my Raspberry Pi project.

Step 1 – Create an Account

It was quick and easy to sign up for a free account. This gives you 10 free messages so you’ve got a chance to test your code before having to pay for more messages.

Step 2 – Example Code

Create a Python script on your Pi named “send_sms.py” and include the following content :

#!/usr/bin/python
#-----------------------------------
# Send SMS Text Message
#
# Author : Matt Hawkins
# Site   : http://www.raspberrypi-spy.co.uk/
# Date   : 30/08/2012
#
# Requires account with TxtLocal
# http://www.txtlocal.co.uk/?tlrx=114032
#
#-----------------------------------

# Import required libraries
import urllib      # URL functions
import urllib2     # URL functions

# Define your message
message = 'Test message sent from my Raspberry Pi'

# Set your username and sender name.
# Sender name must alphanumeric and 
# between 3 and 11 characters in length.
username = 'joebloggs@example.com'
sender = 'RPiSpy'

# Your unique hash is available from the docs page
# https://control.txtlocal.co.uk/docs/
hash = '1234567890abcdefghijklmnopqrstuvwxyz1234'

# Set the phone number you wish to send
# message to.
# The first 2 digits are the country code.
# 44 is the country code for the UK
# Multiple numbers can be specified if required
# e.g. numbers = ('447xxx123456','447xxx654321')
numbers = ('447xxx123456')

# Set flag to 1 to simulate sending
# This saves your credits while you are
# testing your code.
# To send real message set this flag to 0
test_flag = 1

#-----------------------------------
# No need to edit anything below this line
#-----------------------------------

values = {'test'    : test_flag,
          'uname'   : username,
          'hash'    : hash,
          'message' : message,
          'from'    : sender,
          'selectednums' : numbers }

url = 'http://www.txtlocal.com/sendsmspost.php'

postdata = urllib.urlencode(values)
req = urllib2.Request(url, postdata)

print 'Attempt to send SMS ...'

try:
  response = urllib2.urlopen(req)
  response_url = response.geturl()
  if response_url==url:
    print 'SMS sent!'
except urllib2.URLError, e:
  print 'Send failed!'
  print e.reason

Step 3 – Run

Assuming your Pi is connected to the Internet you can then run the script using :

python send_sms.py

If everything has worked you should see “SMS Sent!” displayed on your screen.

While you are testing you can make use of the “test_flag”. This allows the script to run but without using up your credits. Make sure you enter your own user name, hash and target mobile phone number. If everything looks good set the flag to “0” and run the script again. This will send a real message to your phone and deduct 1 credit from your TxtLocal account.

Once you’ve used up your initial 10 free messages you can buy additional credits. How expensive this facility becomes is really down to how many messages you get your Pi to send. For my purposes I only intend on sending a few hundred per year.

Important Notes

  • As each message will use up your credits on TxtLocal so you should consider carefully how many messages your script sends. Any programming mistakes may result in you sending more messages than you planned.
  • Make sure you enter the mobile phone number correctly so you do not send messages to the wrong person.
  • The link I provide above to TxtLocal is an affiliate link. This means if you sign up using it any purchases you make via their system will earn me a small amount of commission. You don’t have to sign up via this link if you don’t want to but there is no reason not to.
This entry was posted in Python, Software, Tutorials & Help and tagged , , , , . Bookmark the permalink.



11 Responses to Sending SMS Text Messages Using Python

  1. Kory Prince says:

    Hey Matt!
    Great post. I too was in search of some way to send sms from python.

    However I found what I think might be a better solution.
    Anyone in the US or UK can get a free Google Voice number that will allow you to text for free. (legally.)

    A guy named Ehsan Foroughi created a python library to interface with google voice, and I modified it to send sms messages.

    You can find the code and information here:
    https://github.com/korylprince/pygvoicelib

    Once you get your authentication codes (using the get_auth.py script)

    your sms sending script becomes as easy as:

    import pygvoicelib
    client = pygvoicelib.GoogleVoice(username,apppass,auth_token,rnr_se)
    client.sms(number,txtmsg)

    It’s been very reliable for me as long as I don’t send a bunch of messages at once (like trying to send 100 in a minute.) And it works great on the Pi out of the Box.

    If you can’t get that working, I’ve also had great success with twilio, which has the best prices I could find (in the US) for SMS – $1 per month for a number and $.01 per message.

    Kory

      • Matt says:

        I looked into Google Voice as people kept mentioning it but couldn’t find any decent information on what it actual does and how you could use it via Python. Also I didn’t want to install something on my desktop/mobile just to support a Pi project. So for me TxtLocal is easier to implement and I don’t have to install anything.

        • Kory prince says:

          To Matt, google voice basically gives you a free new number. You don’t have to install anything.
          To do SMS all I need is a python script much like yours.

          You can forward it to your cell phone, etc but you don’t have to.

          Best wishes,

          Kory

          • Matt says:

            Unfortunately information on using Google Voice with Python isn’t easy to find. Google doesn’t make it very clear what Voice actually does. Also whenever I go to the Google Voice page it doesn’t let me do anything but download an application. Not sure if this is because I’m in the UK. It may be more viable in other countries.

    • Robert says:

      Worked first time – thank you.

  2. SteveOll says:

    Your Python code works really well with the TxtLocal provider and I live outside of the UK! (Ireland) I wish that I had this code back in April this year for my 2nd year Mechatronics project at Uni!

  3. Dave Walker says:

    Excellent!

    Thanks for this – just signed up (via your link) and it worked beautifully immediately :o) Nice one!

  4. Martin G says:

    What about using sms gateway or SMS server tools on the Raspberry Pi? I’ve had this working on Ubuntu with a USB 3G dongle but not tried on the Pi. Could be worth a shot, that way you will not have to send the texts to your phone via an external site, but can send straight from the USB device and out.

  5. McZlatan says:

    Nice post… Seems to be exactly what i want.
    I registered and used the script above changing the neccessary things. I got the “sms sent” but my credit wasnt deducted and i also didnt recieve the message too.
    I was wondering what could be wrong.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>