Tuesday, November 27, 2012

Sending an SMS from Raspberry Pi using Python, Gmail

Sending an SMS using Python on the Raspberry Pi is as easy as, well you know, pie.

   1: #!/usr/bin/env python
   2:  
   3: import smtplib
   4: import sys,datetime
   5:  
   6: def sms(user, password):
   7:     """Login and attempt to send message"""
   8:     try:
   9:         mailserver.login(user, password)
  10:     except smtplib.SMTPException:
  11:         print 'Problem logging in'
  12:         sys.exit(1)
  13:     body = 'Test'
  14:     to = '5195554444@txt.bellmobility.ca'
  15:     print 'Sending...\n'
  16:     try:
  17:         mailserver.sendmail(user, to, body)
  18:     except smtplib.SMTPException:
  19:         print 'Couldnt send'
  20:     else:
  21:         print 'Message sent at ' + cCurrentTime = str(datetime.datetime.now())[:19]
  22:     mailserver.quit()
  23:     
  24: if __name__=="__main__":
  25:     mailserver = smtplib.SMTP('smtp.gmail.com')
  26:     print mailserver.ehlo()
  27:     print mailserver.starttls()
  28:     print mailserver.ehlo()
  29:     user = 'yourgmailusername@gmail.com'
  30:     passw = '1a2b3c4d5f'
  31:     sms(user, passw)      

Python 2.7 will already have the smtplib as well as sys installed, so no extras are required.


Simply replace the phone number,carrier,gmail userid as well as gmail password with your own values and it should run.


You can remove the ‘print’ statements from before the mailserver.ehlo, starttls and ehlo methods. They are there just to give you some feedback just in case sending doesn’t work.


My example lists txt.bellmobility.ca as carrier. Yours likely will be different. You can get a list of carriers here.


I am not sure if gmail processes these SMS messages for any carrier outside North America.


Naturally, your recipients won’t be able to respond to your message, so it really should be used to send one way messages only. Such as when you are 5,000 km away on vacation and your homebrew alarm system sends you a message that someone just broke into your front door and absconded with your brand new 60” LED flat panel TV. It is always better to be informed.

3 comments:

Anonymous said...

Hi Krith,

Thank you for the great post. It works great, but I have one noob question, is it possible to send an sms to 3 people at once?

Anonymous said...

Sorry should have been Keith...typo..

Keith Hekker said...

Probably the simplest way would be to add another parameter (SMSRecipient) to the sms method, something like this:

sms(user, password,SMSRecipient)

Then simply add your sms numbers to a list, e.g.
numbers = ['5554441212@mycarrier.ca','5553331212@mycarrier.ca','5552221212@anothercarrier.ca']

Next, replace the very last line, line 31, with
for number in numbers:
sms(user,passw,number)