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.

SMS Gateways

TxtLocal Logo

Sending 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 – Get Your API Hash

You can get your unique API hash from the TextLocal Control Panel. You must enter your API hash into the example script below. Note : This is not the same as the “API Key”.

Step 3 – Example Python Code

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

# Send SMS Text Message using Python
# Author : Matt Hawkins
# Site   :
# Date   : 29/06/2018
# Requires account with TxtLocal
# Import required libraries
import urllib      # URL functions
import urllib2     # URL functions

# Set YOUR TextLocal username
username = ''

# Set YOUR unique API hash (NOT API Key)
# It is available from the docs page
apihash = '1234567890abcdefghijklmnopqrstuvwxyz1234'

# Set a sender name.
# Sender name must alphanumeric and 
# between 3 and 11 characters in length.
sender = 'RPiSpy'

# 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

# 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')

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

# No need to edit anything below this line

values = {'test'    : test_flag,
          'username': username,
          'hash'    : apihash,
          'message' : message,
          'sender'  : sender,
          'numbers' : numbers }

url = ''

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

print('Attempt to send SMS ...')

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

This script can be downloaded directly to your Pi from BitBucket using :


or by using this link.

You can edit the script at anytime using :


Step 4 – Run & Send SMS

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


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

  • You must edit the script to include YOUR own API hash and YOUR own username.
  • 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.


  1. 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:

    Once you get your authentication codes (using the script)

    your sms sending script becomes as easy as:

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

    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.


  2. 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. 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.

  4. 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.

    • damtheman2000 on

      Have you ensured you changed the test_flag from 1 to 0?

      I forgot to change that after my eagerness to see the script work – which works splendidly 🙂

      And yes, hello from 2015 Mr September 2014 user!

  5. Ashok Subramaniam on

    I get the msg “SMS sent” but the msg is not actually been sent. the txtlocal account works as I am able to send SMS from it. Please help Ashok

  6. Hello,
    nice post, but i’ve a problem … im not reciving sms, i get the message ‘SMS SENT’ txtlocal account works, i can send sms from web. help me please ;'(

  7. HI,

    I did the necessary changes. When I run the script , i get the below output but no sms.
    set the test_flag=0 and I am trying for US Number. Any Suggestions.

    Attempt to send SMS …
    SMS sent!

  8. hi
    Im facing the same issue. It says the sms is being sent but no sms is received. Im sending the msg to an Indian number. Plus is it necessary that i run this code on pi ? Please reply

  9. This doesn’t seem to work any more I have recently tried it. Website info must be out of date and yes I set it to 0.

    • Download the script again and give it a try. I’ve updated a few things as the API had changed. As long as you put in valid username, apihash and numbers it should be fine now.

    • The international dialling code for the US is 1. So in my example code you would replace “44” with “1” for a US cell phone.

  10. Hey Matt,
    i am happy that i found your thread.
    I tried to use the skript and changed the data you told us to.
    But sadly i am always getting this error…

    Traceback (most recent call last):
    File “/home/pi/Desktop/”, line 82
    except urllib2.URLError, e:
    SyntaxError: invalid syntax

    Maybe because i run Python 3.7.3?
    Any tips or ideas?

    Kind Regards

    • I was attempting to update this code to work with Python 3 but unfortunately my TextLocal account doesn’t work anymore. I’ve emailed their support. If they fix my account I’ll update the script. If they don’t I’ll stop directing people to their service. Let’s see what happens …

  11. Hi Matt,

    Good news, Your Script works, I thought I had the same issue as some of your forum posters, SMS sent but no text message to smart phone. I called support and checked my account, for some reason I had been given an American IP address. I am UK based. Once this was changed I sent an SMS message and got a text to my smart phone. My project involves three Raspberry Pis and all three have sent me sms messages. Thanks Matt.

Leave A Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.