Create a gist now

Instantly share code, notes, and snippets.

anonymous /
Created Aug 12, 2013

#!/usr/bin/env python2
from __future__ import absolute_import, division, print_function
from datetime import datetime, timedelta
import os
import sys
import bs4
import dateutil
import dateutil.parser
import httplib2
import notify2
import pytz
import toml
config_path = '%s/ag/gmail.toml' % os.getenv('XDG_CONFIG_HOME')
last_path = '%s/ag/gmail-last-check' % os.getenv('XDG_CONFIG_HOME')
timezone = pytz.timezone('US/Eastern')
now = pytz.utc.localize(datetime.utcnow())
config = toml.loads(open(config_path).read())
feed = ''
last_check = open(last_path).read().strip()
last_check = dateutil.parser.parse(last_check)
# Avoid out of range errors by using something a little above the min.
last_check = pytz.utc.localize(datetime.min + timedelta(hours=25))
# Fetch the unread emails.
h = httplib2.Http(timeout=10)
h.add_credentials(config['username'], config['password'])
resp, content = h.request(feed)
if resp['status'] != '200':
print >> sys.stderr, resp
soup = bs4.BeautifulSoup(content)
if not soup.find('feed'):
print >> sys.stderr, "Invalid XML data."
print >> sys.stderr, resp
# Find all emails that were retrieved after the last check time
# and launch a notification.
for entry in soup.find_all('entry'):
issued = dateutil.parser.parse(entry.find('issued').get_text())
if issued < last_check:
frm = entry.find('author').find('name').get_text()
subject = entry.find('title').get_text()
summary = entry.find('summary').get_text()
nicetime = issued.astimezone(timezone).strftime('%H:%M')
header = '%s - %s (%s)' % (subject, frm, nicetime)
n = notify2.Notification(header, summary)
# We've gathered the email, so report that we checked it.
print(now.strftime('%Y-%m-%dT%H:%M:%SZ'), file=open(last_path, 'w+'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment