diff options
author | Marius Halden <marius.h@lden.org> | 2015-04-12 03:09:43 +0200 |
---|---|---|
committer | Marius Halden <marius.h@lden.org> | 2015-04-12 03:09:43 +0200 |
commit | 322dbfa707da60674eccc2dda449a9815bd4f69a (patch) | |
tree | 69c55f5265cb1b7605b426970138bf3781dff5a1 | |
parent | e93959a878a5ecf14d8b434a19b69f4fc077427b (diff) | |
download | email2push-322dbfa707da60674eccc2dda449a9815bd4f69a.tar.gz email2push-322dbfa707da60674eccc2dda449a9815bd4f69a.tar.bz2 email2push-322dbfa707da60674eccc2dda449a9815bd4f69a.tar.xz |
Handle multipart and some comments
-rwxr-xr-x | push.py | 31 |
1 files changed, 28 insertions, 3 deletions
@@ -9,8 +9,10 @@ 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: @@ -24,42 +26,65 @@ 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 -if not api_token or not user_tokens: +# 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') -payload = mail.get_payload(decode=True) -encoding = mail.get_charsets()[0] +# 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) |