Last active
March 5, 2016 22:53
-
-
Save julianandrews/e7f7d4024b1589ba4fed to your computer and use it in GitHub Desktop.
Simple script to check your gmail inbox, suitable for use with i3status, xmobar or anything that can run scripts and use the output.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
import argparse | |
import getpass | |
import keyring | |
import requests | |
import sys | |
import xml.etree.ElementTree | |
SERVICE_NAME = 'gmail-count' | |
def get_url(email_address): | |
localpart, _, domain = email_address.rpartition('@') | |
if domain == 'gmail.com': | |
return 'https://mail.google.com/mail/feed/atom/' | |
else: | |
return 'https://mail.google.com/a/%s/feed/atom/' % domain | |
def get_count_from_xml(xml_string): | |
tree = xml.etree.ElementTree.fromstring(xml_string) | |
node = tree.find('{http://purl.org/atom/ns#}fullcount') | |
return node.text | |
def get_mail_count(email_address): | |
url = get_url(email_address) | |
password = keyring.get_password(SERVICE_NAME, email_address) | |
if password is None: | |
print("No password found for '%s'." % email_address, file=sys.stderr) | |
return | |
auth = requests.auth.HTTPBasicAuth(email_address, password) | |
response = requests.get(url, auth=auth) | |
if response.status_code == 200: | |
try: | |
return get_count_from_xml(response.content) | |
except xml.etree.ElementTree.ParseError: | |
print("Failed to parse XML:\n%s" % xml_string, file=sys.stderr) | |
else: | |
print("Request failed:\n%s" % response.content, file=sys.stderr) | |
def parse_args(): | |
parser = argparse.ArgumentParser(description='Check gmail message count.') | |
parser.add_argument( | |
'-s', | |
'--set-pass', | |
dest='set_pass', | |
action='store_true', | |
default=False, | |
help='set the password for email_address', | |
) | |
parser.add_argument( | |
'-d', | |
'--delete-pass', | |
dest='delete_pass', | |
action='store_true', | |
default=False, | |
help='delete the password for email_address' | |
) | |
parser.add_argument('email_address', help='Email Address') | |
return parser.parse_args() | |
if __name__ == '__main__': | |
args = parse_args() | |
if args.set_pass and args.delete_pass: | |
raise parser.error('-s and -d are mutually exclusive') | |
elif args.set_pass: | |
password = getpass.getpass() | |
keyring.set_password(SERVICE_NAME, args.email_address, password) | |
elif args.delete_pass: | |
keyring.delete_password(SERVICE_NAME, args.email_address) | |
else: | |
print(get_mail_count(args.email_address) or '?') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've gone ahead and made a proper repo for this script:
I was fiddling with it compulsively, and it seemed worth the trouble: