SMS + libgmail + cron = All sorts of fun

Part 2 is a more direct example of libgmail and does something more interesting.


Part 1 - The Email Notifier

This started out as just a simple way for me to see if I had any messages sitting in my gmail account when I was away from a computer and only had the terrible browser in my phone to check with. I didn't actually want to read the spam messages, so just forwarding them doesn't quite work.

There are two main ingredients:

I have two gmail accounts. The first one is the one I care about; the second is for junk. We are going to check the account I care about see if there are any messages and if so, send my cellphone a message from the junk account telling me who sent the new message.
#!/usr/bin/python
# gmail-notifier.py
import libgmail

if __name__ == "__main__":
    caredFor = libgmail.GmailAccount("caredForGmail", "caredForPassword")
    junky = libgmail.GmailAccount("junkyGmail", "junkPassword")
    
    caredFor.login()
    junky.login()

    if caredFor.getUnreadMsgCount():
        folder = caredFor.getUnreadMessages()
        for thread in folder:
            for msg in thread:
                junky.sendMessage(libgmail.GmailComposedMessage("cellphone", "", "Email from: " + msg.author))

And that is it.

I can get away with sending myself a message for every new mail, for now anyway, because I don't get much mail there and what I do get tends to be important. I also only run this when I'm away from a computer -- which is not often.

Now I just have to get it to run every 10 minutes. I can just add the following to my crontab, and remove it when I'm done, and add it again, and remove it again. Then add it. Then remove it. Then remove it. Then add it. Then add it. Did I remember to remove it last time I added it?

*/10 * * * * /home/username/bin/gmail-notifier.py  
Instead, I wrote a little bash script. So when I go out into the wilderness:
offsite on
and when I return:
offsite off

The hard part was remembering sed -i. IN-PLACE. Very important. Must remember in the future.

#!/bin/bash
# offsite 
echo "Turning the offsite script $1."

if [ "$1" = "on" ]; then
  # make sure there are no identical jobs laying around
  sed --in-place '/gmail-notifier.py/d' crontab.con
  
  # newline - just in case there isn't a newline at the end of the file
  echo >> crontab.cron
  
  # add the job
  echo '*/10 * * * * /home/user/bin/gmail-notifier.py' >> crontab.cron

  # clean up the crontab of rogue newlines (like the one we probably added above)
  sed --in-place '/^$/d' crontab.cron

  #update cron
  crontab crontab.cron

elif [ "$1" = "off" ]; then
  # remove the job from the crontab file
  sed --in-place '/gmail-notifier.py/d' crontab.cron

  #update cron
  crontab crontab.cron

else
  echo "The only available options are on or off."
fi

It has been working well. I am chuffed.

April 14, 2009


Home