topamax once a day

Easily connect Raspberry Pi to Gmail, Facebook, Twitter & more!

  

Easily connect your Raspberry Pi to web services and social networks! This tutorial demonstrates how to painlessly send and receive Gmail on the Raspberry Pi from Python, which in turn, allows you to easily connect it to web services and social networks like Facebook, Twitter, and more! This would normally be well beyond the abilities of most users due to the inherent complexities of programming through social media APis, client/server authentication, etc. However, with the easy-to-use web service Swiss Army knife ifttt (if this then that) anyone with even the most basic programming skills can dramatically expand the capabilities of their Raspberry Pi.

How does this work?

If you are not yet aware, ifttt is a great tool to simplify interaction with many social networks and other web services. It operates with the premise that when some specific action occurs it should perform some other predefined action. The interface is intuitive and very easy to quicky understand. The bridge then is connecting the Raspberry Pi to any of these supported services, which in turn, enables the use of all other services that can respond to that respective trigger. In an earlier  tutorial, I  previously demonstrated how to connect your Raspberry Pi to your Dropbox account using SSHFS. This is another perfectly viable option to establish two way communication with ifttt. However, instead of using email as the primary communication medium, it relies on Dropbox and the filesystem itself. Depending on your application, this may or may not be a better option.

Getting Started

The tutorial uses the most recent Raspbian wheezy image, (2012-08-16-wheezy-raspbian)but should largely generalize for not only other Raspberry Pi distributions, but most other linux distributions as well (especially those derived from Debian, such as Ubuntu and Mint). The majority of the complexity and functionality comes from the feedparser Python module, which should be available essentially anywhere with Python support, even including Windows and OSX distributions too. In any case, begin by setting up the necessary accounts.

Account Setup

As you would undoubtedly expect, the ability to send and receive Gmail is predicated upon having a Gmail account. You are welcome to use your personal Gmail account if you wish, however, I recommend creating a separate account for the Raspberry Pi as it provides the most flexibility. If you would like to expand beyond the capabilities of Gmail on the Raspberry Pi, you will also need an account on ifttt. As with Gmail, you can either share your accounts with the Raspberry Pi, or create a separate account specifically for this purpose. Your decision here might be dependent on which services will be necessary for your own specific application.

Install Packages

Independent of whether you are using one or multiple Gmail or ifttt accounts, you will first need to install some required packages. Open up a terminal on the Raspberry Pi and install the Python development headers and the pip package manager:

sudo apt-get install python-pip python2.7-dev

Next, for pip to work correctly you will need to update to a newer version of distribute using the easy_install utility:

sudo easy_install -U distribute

Once that completes, install the feedparser module with the pip package manager:

sudo pip install feedparser

Now that all of the prerequisites are installed, we can move on to the actual code!

Checking Gmail by the Raspberry Pi

This is an example script that will check the Gmail of the specified user, and display the subject line of all unread e-mails.

 

Sending Gmail from the Raspberry Pi

This is an example script that can be used to send plain text e-mails with Gmail to the specified mail to e-mail address.

 

Sending Attachments through Gmail from the Raspberry Pi

This is a more complex example script that can be used to attach files to emails sent from Gmail. It sends an array of attached files to an array of recipients.

 

Scheduling tasks with cron

Often, we want to run tasks at periodic intervals, like to poll Gmail for example. Cron, the UNIX time-based job scheduler, is an easy way to run regular tasks on the Raspberry Pi (or other *nix). Cron is a daemon (like a Web server) that is used to execute commands or scripts automatically at a specified time and date interval. To use it, open the global crontab (cron table) for editing:

sudo crontab -e

In the text editor, you’ll see a commented out section of text describing how to configure tasks with cron. To add your own task, simply add a line to the end of the file. For example, to run the check_gmail.py script above every minute:

* * * * * python /home/pi/check_gmail.py

Here is a breakdown of what that line actually means, and how you can use to create your own periodic tasks at the desired frequency:

* * * * * command to be executed
- - - - -
| | | | |
| | | | |
| | | | +----- day of week (0 - 6) (0 is Sunday, or use names)
| | | +---------- month (1 - 12)
| | +--------------- day of month (1 - 31)
| +-------------------- hour (0 - 23)
+------------------------- min (0 - 59)

 

Expanding functionality with ifttt

Now that the Raspberry Pi is capable of both sending and receiving e-mails and running scripts at regular intervals we can move on to fun things! The following are some quick examples of the types of things this interface enables. This list is FAR from inclusive, there are literally thousands of possible combinations!

Facebook and Twitter

Update your Facebook status, or post tweets based on raspberry pi events.

Alternatively, create a Facebook or Twitter account specifically for the Raspberry Pi, and have it update its own status messages and post its own tweets.

 

Google Calendar

Automatically send alerts for events that match certain criteria within your Google calendar to the Raspberry Pi. Use this to make things like physical notifiers for holidays or other calendar events.

 

SMS and Phone

Receive SMS notifications or phone calls based on events from the Raspberry Pi. Notify based on certain sensor values, or create your own DIY security system, for example.

 

Weather and Stocks

It’s also easy to control the Raspberry Pi based on the weather forecast. For example, send notifications of impending severe weather or extreme temperatures.

Or create physical notifiers that perform actions whenever a specified stock price exceeds or falls below a specified threshold.

 

Limitations

There are, of course, a few limitations from using Gmail and cron as the primary basis for communication to the cloud. Cron jobs can only be scheduled at minute granularity, that is, they can be scheduled to occur at maximum frequency of one minute intervals. This is acceptable for most tasks, though it does however leave a bit to be desired for the more ‘real time’ applications like turning on and off lights, or remotely operated robotics.

 

32 Comments

  1. Newcomer to Python & Raspberry Pi; this tutorial looks incredible; exactly what I was hoping to do. I had no problems going through the various python, easy_install and feedparser installs, and I got Adafruit’s gmail script (http://bit.ly/RxbXd1) to work, but I’ve been unable to get the “checking gmail” and “sending gmail” scripts to work. I get an error: import: not found, USERNAME: not found, PASSWORD: not found and finally a “syntax error: “(” unexpected. Any tips or pointers? Many thanks. John from nyccnc.com.

    • I can’t know for sure without seeing what you, but here are some thoughts. Username and Password refer to your username and password, if you typed the scripts in precisely using the words ‘username@gmail.com’, it’s not going to work.

      “(” unexpected means what it says. somewhere there is a “(” that’s not supposed to be there. Count the “(” and “)” you have and make sure they all match .
      Am error that simply says import not found is odd because import should be a basic statement. make sure it’s typed right. If it said import stmplib missing or something like that you would know that that module isn’t on the Pi (or is in the wrong directory) and you could fix that.

    • It looks like your scripts are not being interpreted as shell scripts, not by the python interpreter. Would adding
      #!/usr/bin/env python
      as the first line help?

      • You’re right, it should probably be there to make sure it is interpreted as a Python script. I went ahead and added the the lines to the gists above

  2. Sending Gmail works well, but Checking Gmail not works:
    File “checkmail.py”,line 7 in unread_count =int(response["feed"]["fullcount"])
    File “/usr/local/lib/python2.7/dist-packages/feedparser.py”,line 383,in getiitem return dict.__getitem__(self,key)

  3. Thanks for your post, as a Python noob I’m having some fun with this. …

    You can use this technique to query a Twitter feed directly as long as it is a public feed. Modifying the get_gmail script …

    import feedparser

    USERNAME = “Raspberry_Pi”

    response = feedparser.parse(“https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=” + USERNAME)

    for i in range(0,5):
    print “(” + str((i+1)) + “/” + str(5) + “) ” + response['items'][i].title

  4. Got it to work! I’m a newcomer to Python (using a Raspberry Pi). Ends up that I have to add the line “#!/usr/bin/env python” at the beginning of the script. I saw this in another program which ran without error. I didn’t think it would impact anything since the line started with a hash (comment??) but it fixed it.

    • #! is special, it lets the shell know what to do with the file. If you don’t put it there you can still run it with ..

      python

      you will see similar lines in any script that needs an interpreter to run.

  5. this may be a silly question but how do i remove “text_file.txt” from being attached?

    • If you don’t want to send an attachment you can just use the send_gmail.py script above the send_gmail_attachment.py script.

  6. confused

    For all us windozers… I was wondering where I install the script.

    I looked at Linux based systems a decade ago, but want to get started with my pi

    Ignorance is not bliss :-(

    • You don’t actually need to install the script. This, and any script can be run from anywhere that you like! However, I suspect you are interested in how to add the script to the system path. To view the current path, you can take a look at the $PATH environmental variable, on the command line, run:
      echo $PATH
      This will show you a list of everywhere the system will look for scripts and binary executables. Add the script to any of the locations specified in the $PATH variable and it will be available to you on the terminal.

  7. I was able to make the send_gmail.py script work EXCEPT to another gmail account. I can send sms to my cellphone using xxx-xxx-xxxx@vtext.com, I can send to my corporate email account but I can not recieve the message to my personal GMail account. When I go into my Pi’s Gmail I see the sent message there but they do not make it over to my personal GMail account. Is this a problem with the interface to GMail?? any one with ideas?

    thanks for sharing this excellent example.
    dwight

  8. I’ve been trying for a couple of days to get the send_gmail.py to work and I keep getting an authentication error, user name and password not accepted. I’ve double and tripple checked but can’t get it working. Any ideas?
    smtplib.SMTPAuthenticationError: (535, b,5.7.1 Username and Password not accepted. Learn more at\n5.7.1 http://support…….. (also, can’t get that support link to work, either)

  9. Well, we figured it out. Apparently, you have to authorize applications in your Gmail account, now, and generate a password. Once I did this, everything worked fine (in case some actually does read my question, above, or has the same problem.

  10. Looks like your scripts have disappeared :(

  11. Tricia D

    This is my first attempt at Linux. I am trying to get motion files emailed to me. How would I change the script to send the .avi files in /tmp/motion as attachments?
    any help greatly appreciated!!
    thanks!

  12. I installed python-pip, distribute and feedparser without issue. I’m able to send email ok however I can’t run the check_gmail.py script because i get I get an ImportError:
    “No module named feedparser “. However if I run # pip freeze feedparser is included in the list.

    Please note : I’m running Python 3.2
    feedparser ==5.1.3

    Thanks, herb

  13. This is awesome :D Is it free for use?

  14. Cocc0lin0

    i’m able to send email but i cant run the check_gmail.py i receive that error

    File “./check_gmail.py”, line 11
    print “(” + str((i+1)) + “/” + str(unread_count) + “) ” + response['items'][i].title
    ^
    IndentationError: expected an indented block

    • Cocc0lin0

      solved it was a tab/space problem but now i have that error:

      Traceback (most recent call last):
      File “./check_gmail.py”, line 11, in
      print “(” + str((i+1)) + “/” + str(unread_count) + “) ” + response['items'][i].title
      IndexError: list index out of range

  15. This is exactly what I was looking for. You’ve saved me a ton of time researching and writing my own stuff.This is fantastic stuff, thanks a lot!

  16. Thank you very much for this howto, the checking gmail script works nice but now I want to take it to the next level: if a message with a certain subject is received perform a specific action or run a script.

    I’ve googled around and a lot of people seem to do this with procmail but there must be a way to do this in Python, the following POP3 script comes close:

    —- begin python POP3 checker —
    import poplib
    from email import parser

    pop_conn = poplib.POP3_SSL(‘pop.gmail.com’)
    pop_conn.user(‘username’)
    pop_conn.pass_(‘password’)
    #Get messages from server:
    messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
    # Concat message pieces:
    messages = [“\n”.join(mssg[1]) for mssg in messages]
    #Parse message intom an email object:
    messages = [parser.Parser().parsestr(mssg) for mssg in messages]
    for message in messages:
    print message['subject']
    pop_conn.quit()
    —- end python POP3 checker —

    But how do I trigger an even on a specific subject ?

    Thanks a lot,
    David

  17. Thank you so much for this code. This is exactly what I need for a tech demonstration at a college fair comming up, only problem is I get an error when I try and check gmail. I am running this file in IDLE3

    I installed the required libraries you described and copied and pasted the code changing my username and password appropriately.

    I get a Syntax error in the line:

    print “(” + str((i+1)) + “/” + str(unread_count) + “) ” + response['items'][i].title

    It doesn’t like the second ” character. I read everyone’s comments and didn’t see a way to fix it.

    Any input would be GREATLY appreciated. I’m new to pi and python.

  18. I’d like to see an example of reading the body of the message.

  19. Chandan

    Nice tutorial, this tutorial also work for Beaglebone Black.
    thanks

Trackbacks/Pingbacks

  1. Easily connect Raspberry Pi to Gmail, Facebook, Twitter & more! #piday #raspberrypi @Raspberry_Pi « adafruit industries blog - [...] Easily connect Raspberry Pi to Gmail, Facebook, Twitter & more! @ MitchTech. Easily connect your Raspberry Pi to …
  2. Raspberry Pi email/SMS doorbell notifier + picture of the person ringing it | Martin's corner on the web - [...] lets create the mailing script, what I used is the “Sending Attachments through Gmail from the Raspberry Pi” [...]
  3. Easily connect Raspberry Pi to Gmail, Facebook, Twitter & more! | MitchTech | Bee thought this. - [...] Easily connect Raspberry Pi to Gmail, Facebook, Twitter & more! | MitchTech. [...]
  4. I2C + Raspberry Pi + Arduino Uno + RPi Camera Board | All that Jaz - [...] Update: I’ve included a function that emails the picture taken to my GMail account. MitchTech has a great tutorial …
  5. Twitter on Raspberry Pi | Raspberry Pi Wonderland - […] 1. Easily connect Raspberry Pi to Gmail, Facebook, Twitter & more! […]
  6. Raspberry Pi + email | RaspberryPi Greenhouse - […] http://mitchtech.net/connect-raspberry-pi-to-gmail-facebook-twitter-more/ […]
  7. Sending Prowl Notifications to an iOS Device from a Raspberry Pi | minordiscoveries - […] otherwise) and an internet connected Raspberry Pi, I’m thinking of using email, as it’s possible to access a gmail …
  8. Two Tone Detect and Twitter - The RadioReference.com Forums - […] I was just reading on this a week or so ago. Easily connect Raspberry Pi to Gmail, Facebook, …
  9. Raspberry Pi Photo Booth • Drumminhands Design - […] They work, but are slow. I didn’t want the guests waiting too long. Instead I used a technique of …

Leave a Reply