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 script above every minute:

* * * * * python /home/pi/

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.



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.


  • Pingback: Easily connect Raspberry Pi to Gmail, Facebook, Twitter & more! #piday #raspberrypi @Raspberry_Pi « adafruit industries blog()

  • 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 ( 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

    • Chrisfs

      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 ‘’, 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

    • You are a wanker John

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

    • Weft

      I got the same message? Any tips for a complete n00b?

      • TS

        Same problem. Any tips?

        • Type:
          sudo apt-get update
          sudo reboot

          Wait until it reboots and try again. Worked for me!

  • Bruce

    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(“” + USERNAME)

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

  • John

    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.

    • BruceR

      #! 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 ..


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

      • BruceR

        that line should read
        python filename

  • 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 script above the script.

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

  • Dwight

    I was able to make the script work EXCEPT to another gmail account. I can send sms to my cellphone using, 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.

  • Tom Seay

    I’ve been trying for a couple of days to get the 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)

  • tom

    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.

  • Looks like your scripts have disappeared 🙁

    • ignore that – not sure what happened there!!!!

  • 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!!

  • Herb

    I installed python-pip, distribute and feedparser without issue. I’m able to send email ok however I can’t run the 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

  • This is awesome 😀 Is it free for use?

  • Cocc0lin0

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

    File “./”, 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 “./”, line 11, in
      print “(” + str((i+1)) + “/” + str(unread_count) + “) ” + response[‘items’][i].title
      IndexError: list index out of range

      • jp

        I found that there were too many unread emails.

  • Pingback: Raspberry Pi email/SMS doorbell notifier + picture of the person ringing it | Martin's corner on the web()

  • Pingback: Easily connect Raspberry Pi to Gmail, Facebook, Twitter & more! | MitchTech | Bee thought this.()

  • 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!

  • Pingback: I2C + Raspberry Pi + Arduino Uno + RPi Camera Board | All that Jaz()

  • David

    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(‘’)
    #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’]
    —- end python POP3 checker —

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

    Thanks a lot,

  • Pingback: Twitter on Raspberry Pi | Raspberry Pi Wonderland()

  • John

    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.

    • Coper

      It does NOT work! The author did nt why?????

  • Pingback: Raspberry Pi + email | RaspberryPi Greenhouse()

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

  • Pingback: Sending Prowl Notifications to an iOS Device from a Raspberry Pi | minordiscoveries()

  • Pingback: Two Tone Detect and Twitter - The Forums()

  • Chandan

    Nice tutorial, this tutorial also work for Beaglebone Black.

  • Pingback: Raspberry Pi Photo Booth • Drumminhands Design()

  • Pingback: How can I get my Pi to check/read email to trigger an event? | CL-UAT()

  • Hello, I’ll get right to it:
    In the file “Sending Attachments through Gmail from the Raspberry Pi”
    I have the lines
    # sendMail( [“”],
    sendMail( [“”],
    “Testing for images from rPi – Subject from rpi”,
    “Testing for images from rPi – Body from rpi “,
    [“/home/pi/image.jpg”] )
    Sending to has no joy.
    Sending to is much joy.

    So I think that Tumblr only wants email posts from “”, Oh No I’m wrong again Tumbler accepts post from anyone as long as they have the correct “@tumbler” address.

    Sending to,, and GMX,com is much joy.

    BTW “Sending Gmail from the Raspberry Pi” has much joy.

    BTW “” is not my real address for but is me! Thank you so much if you can help me with this problem. Thank you so much if you cannot for I have received lots, lots of knowledge from reading and using your code. Thank you Thank. you.

    Please help my head is almost bald and the hair pile is on the wall. :-}

  • Lorenzo

    i want to have a light blinking when i got an email how can i do that?

  • Pingback: How can I get my Pi to check/read email to trigger an event? | DL-UAT()

  • Nick


    Any ideas of how I can automatically upload a photo (taken from a web cam) from Raspberry Pi to a Facebook profile?


  • san

    can some one help me i got the following error when i executed the

    File “”, line 53, in
    File “”, line 27, in loop
    server.login(USERNAME, PASSWORD)
    File “/usr/local/lib/python2.7/dist-packages/imapclient/”, line 161, in login
    return self._command_and_check(‘login’, username, password, unpack=True)
    File “/usr/local/lib/python2.7/dist-packages/imapclient/”, line 987, in _command_and_check
    typ, data = meth(*args)
    File “/usr/lib/python2.7/”, line 507, in login
    raise self.error(dat[-1])
    imaplib.error: [ALERT] Please log in via your web browser: (Failure)

    • Steve

      San – I just setup this program and got it working. At first, Google sent me this message: which explains how to set your gmail account for “Allowing less secure apps to access your account” The python program above under the heading “Sending Attachments through Gmail from the Raspberry Pi” worked fine after I changed to the less secure” option in gmail

      However, I wonder if anyone has an updated instructions for python code that uses “modern security standards” so I don’t have to leave my google account in “less secure” mode. Complete examples or hints/suggestions will both be appreciated!

      • san

        thanks steve it worked

  • Pingback: Raspberry Pi Surveillance Camera()

  • Carlos Wistuba G.

    Thank you very much for this tutorial, i’ve just want to add an update for the non-english people like me, because i had a few issues related to the enconding (special characters) so, you can update some lines to encode the variable string received, on this two lines of the code:

    response = feedparser.parse(unicode(“https://” + USERNAME + “:” + PASSWORD + “”).encode(“utf-8”))

    print “(” + str((i+1)) + “/” + str(unread_count) + “) ” + unicode(response[‘items’][i].title).encode(“utf-8”)

    As you can see, the strings from the query and responde are encoded to UTF-8.

    I hope it can be usefull


  • Pingback: Raspberry Pi Social Media Connecter - BotZone()

  • Pingback: Video Marketing As The Fastest Way To Make Money | Kookii's Garden in South Texas()