anonymous / bingmail-notifier.py
Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

bin/gmail-notifier

View bingmail-notifier.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
#!/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
 
notify2.init('gmail-notifier')
 
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 = 'https://mail.google.com/mail/feed/atom'
try:
last_check = open(last_path).read().strip()
last_check = dateutil.parser.parse(last_check)
except:
# 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
sys.exit(1)
 
soup = bs4.BeautifulSoup(content)
if not soup.find('feed'):
print >> sys.stderr, "Invalid XML data."
print >> sys.stderr, resp
sys.exit(1)
 
# 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:
continue
 
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)
n.set_timeout(10000)
n.show()
 
# 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
Something went wrong with that request. Please try again.