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
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 “sendsms.py” and include the following content :
#!/usr/bin/python #----------------------------------- # Send SMS Text Message using Python # # Author : Matt Hawkins # Site : https://www.raspberrypi-spy.co.uk/ # Date : 29/06/2018 # # Requires account with TxtLocal # http://www.txtlocal.co.uk/?tlrx=114032 # #----------------------------------- # Import required libraries import urllib # URL functions import urllib2 # URL functions # Set YOUR TextLocal username username = 'joebloggs@example.com' # Set YOUR unique API hash (NOT API Key) # It is available from the docs page # https://control.txtlocal.co.uk/docs/ 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 = 'https://api.txtlocal.com/send/' 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)
This script can be downloaded directly to your Pi from BitBucket using :
wget https://bitbucket.org/MattHawkinsUK/rpispy-misc/raw/master/python/sendsms.py
or by using this link.
You can edit the script at anytime using :
nano sendsms.py
Step 4 – Run & Send SMS
Assuming your Pi is connected to the Internet you can then run the script using :
python sendsms.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
- 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.
34 Comments
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
Has Google Voice launched properly in the UK?
http://thenextweb.com/google/2012/08/25/what-ever-happened-google-voice-launching-europe/
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.
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
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.
Worked first time – thank you.
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!
Good to hear its been useful!
Excellent!
Thanks for this – just signed up (via your link) and it worked beautifully immediately :o) Nice one!
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.
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.
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!
Hello,
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
So Useful information.
Can I ask a Question?
What is Country code for Korea?
The international dialing code for South Korea is 82.
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 ;'(
Assuming you’ve got credits in your txtlocal account, did you set the test_flag to 0?
I am getting the same problem and have already set the test_flag to 0
Works brilliantly, thanks for taking the time to share it.
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!
What does the log say on the TextLocal site?
hi
i also facing same problem, i run script ,script executed but not receiving sms on the number,
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
Check the online dashboard to see if there is any record of the service receiving your request to send.
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.
What is country code for US?
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.
where do you get the username of your account??
It’s the username you use to login to the account.
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/sms.py”, line 82
except urllib2.URLError, e:
^
SyntaxError: invalid syntax
Maybe because i run Python 3.7.3?
Any tips or ideas?
Kind Regards
Chris
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 …
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 txtlocal.co.uk 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.
Thanks for confirming! I was wondering if the service just didn’t work anymore. Good to hear it’s still an option.