get_email_header (754B)
1 #!/usr/bin/env python3 2 # adapted from https://stackoverflow.com/a/39464990/414272 3 4 from email.parser import BytesParser 5 from email.header import Header, decode_header 6 from email.errors import HeaderParseError 7 from sys import argv, stdin 8 9 header = argv[1] 10 11 # TODO: for some reason this does not work when piping 12 message = BytesParser().parse(stdin.buffer) 13 try: 14 subj = ''.join([ 15 frag.decode(enc if enc else "utf-8") 16 if isinstance(frag, bytes) else frag 17 for frag, enc in decode_header(message[header])]) 18 except (HeaderParseError, UnicodeDecodeError): # maybe warn about error? 19 subj = message['subject'] 20 subj = subj.decode("utf-8") if isinstance(subj, bytes) else subj 21 print(subj.strip().replace('\n', '')) 22 23