input notmuch json, output clean useful json | js '.[] | {from, subject, date}'
5M2FYS5GTEPSCGLG6VPUMFXTKCP7ETDIOVOC2YSEGQHGKG3IFMKQC
#! /usr/bin/env python3
import json
import os
import sys
from stat import S_ISFIFO
def extract_email_objects(notmuch_blob):
for email in notmuch_blob:
e = email
email_object = None
while email_object is None:
try:
e.get('body')
except AttributeError:
e = e[0]
continue
email_object = e
yield email_object
def parse_emails(blob):
emails = (e for e in extract_email_objects(blob) if e['headers']['From'] != 'ccummings@eventbrite.com')
for email in emails:
tags = email['tags']
date = email['headers']['Date']
to = email['headers']['To']
from_address = email['headers']['From']
subject = email['headers']['Subject']
body = email['body']
try:
body = body[0].get('content')[0].get('content').replace('\n\n', '')
except:
pass
yield {"tags": tags, "date": date, "to": to, "from": from_address, "subject": subject, "body": body}
def run(blob):
print(json.dumps(list(parse_emails(blob))))
if __name__ == "__main__":
try:
blob = None
if S_ISFIFO(os.fstat(0).st_mode):
blob = json.loads(sys.stdin.read())
else:
with open(sys.argv[1], mode='r') as f:
blob = json.load(f)
except FileNotFoundError:
print('argument must be a path to a json file', file=sys.stderr)
sys.exit(1)
except IndexError:
print('filename argument is required', file=sys.stderr)
sys.exit(2)
except json.decoder.JSONDecodeError:
print('content is not json encoded', file=sys.stderr)
sys.exit(3)
run(blob)