#!/usr/local/bin/python import os import re import sys import yaml import pushover import email.header import email.parser try: # Use argv[1] as path to config file if specified cfg = sys.argv[1] except IndexError: # Fall back to push.cfg in the same direcetory cfg = os.path.dirname(os.path.realpath(__file__)) + '/push.cfg' with open(cfg, 'r') as fh: maps = yaml.load(fh) sender_map = maps.get('senders', []) recipient_map = maps.get('recipients', []) recipient = os.environ.get('RECIPIENT', '') sender = os.environ.get('SENDER', '') api_token = None user_tokens = None # Make sure we got a sender and a recipient if len(recipient) == 0 or len(sender) == 0: print >>sys.stderr, "recipient or sender missing." sys.exit(1) # Select api key from map based on sender for s in sender_map: if re.match(s.get('re', r'^$'), sender): api_token = s.get('key', None) break # Select user key(s) from map based on sender for r in recipient_map: if re.match(r.get('re', r'^$'), recipient): user_tokens = r.get('keys', None) break # Make sure we have both user and api keys if api_token is None or user_tokens is None: print >>sys.stderr, "found no matching keys for sender or recipient." sys.exit(1) # Read an email from stdin parser = email.parser.Parser() mail = parser.parse(sys.stdin) # Try to get the subject from the email and recode to utf-8 if possible title, encoding = email.header.decode_header(mail.get('subject'))[0] if title is not None and encoding is not None: title = title.decode(encoding).encode('utf-8') # Lets at least try to handle mime multipart if mail.is_multipart(): # Try to find something plain text for payload in mail.walk(): if payload.get_content_type() == 'text/plain': break else: # A realy stupid fallback payload = mail.get_payload(0) else: # Hurray no multipart payload = mail.get_payload(decode=True) # Recode payload to utf-8 if possible encoding = payload.get_charsets()[0] if payload is not None and encoding is not None: payload = payload.decode(encoding).encode('utf-8') msg = payload.strip() # Check for multiple user keys if type(user_tokens) is list: # Send notification to each user key for user_token in user_tokens: p = pushover.Client(user_token, api_token=api_token) p.send_message(msg, title=title) else: # Send notification to the only user key p = pushover.Client(user_tokens, api_token=api_token) p.send_message(msg, title=title)