Facebook Twitter Instagram Pinterest YouTube
    Trending
    • Add Kodi to RetroPie Menu
    • Disable Auto-login in Raspberry Pi OS
    • Raspberry Pi Cloud Storage with MEGA
    • RetroPie Temperature Monitor from Menu
    • Pi Pico Pinout and Power Pins
    • Install Arduino IDE on Raspberry Pi
    • Raspberry Pi 400 SSD Upgrade
    • Raspberry Pi Temperature Monitoring
    Facebook Twitter Instagram Pinterest YouTube RSS
    Raspberry Pi SpyRaspberry Pi Spy
    • Home
    • Categories
      • General
      • Hardware
      • Programming
      • Python
      • Software
      • Tutorials & Help
    • BerryClip
      • BerryClip Instructions
      • BerryClip Plus Instructions
      • Videos & Reviews
    • Buy
      • Buy Pi
      • Buy Pi Accessories
      • Buy Books
    • Tools
      • Ultimate Raspberry Pi Alexa Skill
      • Pi Power Estimator App
      • Pi-Lite 14×9 LED Matrix Sprite Editor
      • RPiREF Pin-out Reference App
      • Simple Ohm’s Law Calculator
      • Web Sites & Links
    • Tutorials & Help
        Featured
        November 9, 20200

        Raspberry Pi Temperature Monitoring

        Recent
        May 6, 2022

        Add Kodi to RetroPie Menu

        February 26, 2022

        Disable Auto-login in Raspberry Pi OS

        February 2, 2022

        Raspberry Pi Cloud Storage with MEGA

      1. Contact Us
      2. Site Map
      Raspberry Pi SpyRaspberry Pi Spy
      You are at:Home»Python»Sending SMS Text Messages Using Python
      Raspberry Pi Python

      Sending SMS Text Messages Using Python

      34
      By Matt on August 30, 2012 Python, Tutorials & Help

      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 “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.
      Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
      Previous ArticleReading Analogue Sensors With One GPIO Pin
      Next Article Checking Raspberry Pi Revision Number & Board Version

      Related Posts

      Add Kodi to RetroPie Menu

      Disable Auto-login in Raspberry Pi OS

      Raspberry Pi Cloud Storage with MEGA

      34 Comments

      1. Kory Prince on September 1, 2012 6:06 am

        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

        Reply
        • Hobbsy on September 12, 2012 1:43 pm

          Has Google Voice launched properly in the UK?

          http://thenextweb.com/google/2012/08/25/what-ever-happened-google-voice-launching-europe/

          Reply
          • Matt on September 13, 2012 7:51 pm

            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.

            Reply
            • Kory prince on September 20, 2012 3:20 am

              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

              Reply
              • Matt on September 20, 2012 10:30 am

                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 on November 5, 2014 3:58 pm

          Worked first time – thank you.

          Reply
      2. SteveOll on September 9, 2012 4:29 pm

        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!

        Reply
        • Matt on September 10, 2012 10:52 pm

          Good to hear its been useful!

          Reply
      3. Dave Walker on September 21, 2012 7:35 pm

        Excellent!

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

        Reply
      4. Martin G on September 30, 2012 12:32 pm

        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.

        Reply
      5. McZlatan on September 29, 2014 11:41 am

        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.

        Reply
        • damtheman2000 on January 6, 2015 5:07 pm

          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!

          Reply
      6. Ashok Subramaniam on December 29, 2014 3:15 pm

        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

        Reply
      7. Simpson on May 29, 2015 1:11 pm

        So Useful information.
        Can I ask a Question?
        What is Country code for Korea?

        Reply
        • Matt on June 4, 2015 7:19 pm

          The international dialing code for South Korea is 82.

          Reply
      8. Pablo on June 5, 2015 4:29 pm

        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 ;'(

        Reply
        • Matt on June 5, 2015 8:49 pm

          Assuming you’ve got credits in your txtlocal account, did you set the test_flag to 0?

          Reply
          • deepak on December 21, 2015 8:13 am

            I am getting the same problem and have already set the test_flag to 0

            Reply
      9. Pete on September 20, 2015 12:20 pm

        Works brilliantly, thanks for taking the time to share it.

        Reply
      10. Ashwani on November 18, 2015 8:53 pm

        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!

        Reply
        • Matt on February 3, 2016 11:16 pm

          What does the log say on the TextLocal site?

          Reply
      11. amar on February 12, 2016 6:16 am

        hi
        i also facing same problem, i run script ,script executed but not receiving sms on the number,

        Reply
      12. THARA on March 6, 2016 12:26 pm

        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

        Reply
        • Matt on July 20, 2016 12:35 pm

          Check the online dashboard to see if there is any record of the service receiving your request to send.

          Reply
      13. Fred on June 30, 2018 3:18 pm

        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.

        Reply
        • Matt on June 30, 2018 9:35 pm

          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.

          Reply
      14. Atos on February 6, 2019 10:25 pm

        What is country code for US?

        Reply
        • Matt on February 6, 2019 10:42 pm

          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.

          Reply
      15. siddharth on June 3, 2019 12:17 pm

        where do you get the username of your account??

        Reply
        • Matt on June 4, 2019 10:55 am

          It’s the username you use to login to the account.

          Reply
      16. Chris on June 11, 2020 9:09 pm

        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

        Reply
        • Matt on June 11, 2020 11:11 pm

          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 …

          Reply
      17. Simon Cumming on February 4, 2021 3:25 pm

        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.

        Reply
        • Matt on February 4, 2021 3:57 pm

          Thanks for confirming! I was wondering if the service just didn’t work anymore. Good to hear it’s still an option.

          Reply

      Leave A Reply Cancel Reply

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

      Recent Posts
      May 6, 2022

      Add Kodi to RetroPie Menu

      February 26, 2022

      Disable Auto-login in Raspberry Pi OS

      February 2, 2022

      Raspberry Pi Cloud Storage with MEGA

      January 7, 2022

      RetroPie Temperature Monitor from Menu

      January 24, 2021

      Pi Pico Pinout and Power Pins

      Categories
      • 1-wire
      • 3D Printing
      • Add-ons
      • BBC Micro:bit
      • BerryClip
      • Books
      • Camera Module
      • Cases
      • Events
      • General
      • Hardware
      • I2C
      • Infographics
      • Interfaces
      • Minecraft
      • Model A+
      • Model B+
      • News
      • Pi Models
      • Pi Zero
      • Power
      • Programming
      • Python
      • Raspberry Pi OS
      • Raspbian
      • RetroGaming
      • Robotics
      • Sensors
      • Software
      • SPI
      • Tutorials & Help
      Tags
      3D Printing Arduino audio battery berryclip Birthday bluetooth cambridge camera CamJam DigiMakers display games GPIO I2C interface Kickstarter LCD LED Linux media Minecraft Model A Model B motionEyeOS PCB photography photos Pi-Lite portable power python Raspberry Jam Raspberry Pi Bootcamp raspbian Retrogaming retroPie screen SD card security sensor SPI temperature ultrasonic video
      Raspberry PI Related
      • Adafruit Blog
      • Average Maker
      • Official RaspBerry Pi Site
      • Raspberry Pi Pod
      • RasPi.tv
      • RaspTut
      • Stuff About Code
      Tech Resources
      • MattsBits – Pi Resources
      • Microbit Spy
      • Technology Spy
      Archives
      About

      Unofficial site devoted to the Raspberry Pi credit card sized computer offering tutorials, guides, resources,scripts and downloads. We hope to help everyone get the most out of their Pi by providing clear, simple articles on configuring, programming and operating it.

      Popular Posts
      September 19, 2014

      Top 5 Reasons The Raspberry Pi Sucks

      July 27, 2012

      16×2 LCD Module Control Using Python

      October 20, 2013

      Analogue Sensors On The Raspberry Pi Using An MCP3008

      Recent Posts
      May 6, 2022

      Add Kodi to RetroPie Menu

      February 26, 2022

      Disable Auto-login in Raspberry Pi OS

      February 2, 2022

      Raspberry Pi Cloud Storage with MEGA

      Facebook Twitter Instagram Pinterest YouTube RSS

      Entries RSS | Comments RSS

      This site is not associated with the official Raspberrypi.org site or the Raspberry Pi Foundation. Raspberry Pi is a trademark of the Raspberry Pi Foundation.

      Copyright © 2022 - All Rights Reserved - Matt Hawkins

      Type above and press Enter to search. Press Esc to cancel.