Skip to content

Instantly share code, notes, and snippets.

@lanmaster53
Last active March 17, 2020 08:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lanmaster53/9f9c6f25701a7f0f1f00 to your computer and use it in GitHub Desktop.
Save lanmaster53/9f9c6f25701a7f0f1f00 to your computer and use it in GitHub Desktop.
Email Attachment Parser
#!/usr/bin/env python
import sys
import email
raw = open(sys.argv[1]).read()
msg = email.message_from_string(raw)
print 'Parsing message...'
for part in msg.walk():
c_disp = part.get('Content-Disposition')
c_type = part.get_content_type()
if c_disp is not None and c_disp.startswith('attachment'):
c_enc = part.get('Content-Transfer-Encoding')
c_name = part.get_filename()
try:
c_content = part.get_payload().decode(c_enc)
except:
continue
with open(c_name, 'wb') as fh:
fh.write(c_content)
print 'Attachment \'%s\' extracted.' % c_name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment