Skip to content

Instantly share code, notes, and snippets.

@yeiichi
Last active July 13, 2024 00:44
Show Gist options
  • Save yeiichi/55c7e605e8f8ceb3f560ee743e90d146 to your computer and use it in GitHub Desktop.
Save yeiichi/55c7e605e8f8ceb3f560ee743e90d146 to your computer and use it in GitHub Desktop.
View & check the headers and attachment filename(s) of an EML file.
#!/usr/bin/env python3
from email.header import decode_header
def check_items(msg_):
"""Extract header items from a msg object and Display them.
Args:
msg_ (email.message.Message)
"""
decoded_header = decode_header(msg_.get('subject'))[0] # (b'\x##', 'utf-8')
subject_string, apparent_encoding = decoded_header # Unpack the tuple
if apparent_encoding is None: # Plain text
sj = subject_string
else: # if base64 encoded
sj = subject_string.decode(apparent_encoding)
dt = msg_.get('date')
fm = msg_.get('from').replace('"', '')
to = msg_.get('to').replace('"', '')
cc = msg_.get('cc').replace('"', '') if msg_.get('cc') else ''
bc = msg_.get('bcc').replace('"', '') if msg_.get('bcc') else ''
ir = msg_.get('in-reply-to') if msg_.get('in-reply-to') else ''
header_items = dict(SUBJ=sj, DATE=dt, FROM=fm, TO=to, CC=cc, BCC=bc, IRTO=ir)
filenames = [i.get_filename() for i in msg_.get_payload() if i.get_filename()]
# Display
for k, v in header_items.items():
print(f'{k:4s}: {v}')
print(f"ATCH: {'0x0A'.join(filenames)}")
if __name__ == '__main__':
check_items(msg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment