Advertisement
otakana

Recursive extract email attachments from maildir

Jun 10th, 2020
1,847
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | None | 0 0
  1. import os
  2. import sys
  3. import mailparser
  4. import hashlib
  5. import traceback
  6. import base64
  7. from mailparser.mailparser import MailParser
  8.  
  9. def write_sample(binary, payload, path, filename):
  10.     if not os.path.exists(path):
  11.         os.makedirs(path)
  12.  
  13.     sample = os.path.join(path, filename)
  14.  
  15.     if binary:
  16.         with open(sample, "wb") as f:
  17.             f.write(base64.b64decode(payload))
  18.     else:
  19.         with open(sample, "w") as f:
  20.             f.write(payload)
  21.  
  22. def write_attachments(attachments, base_path):
  23.     for a in attachments:
  24.         realdir=os.path.dirname(os.path.join(base_path,a["filename"]))
  25.         os.makedirs(realdir,exist_ok=True)
  26.         write_sample(
  27.             binary=a["binary"],
  28.             payload=a["payload"],
  29.             path=base_path,
  30.             filename=a["filename"],
  31.         )
  32.        
  33. for directory, dirnames, filenames in os.walk("."):
  34.     for f in filenames:
  35.         filename=os.path.join(directory,f)
  36.         print("Handling {}".format(filename))
  37.         try:
  38.             with open(filename,"r",encoding="latin-1") as infile:
  39.                 data=infile.read()
  40.                 h=hashlib.sha256(data.encode('utf-16')).hexdigest()
  41.                 outpath="../{}/".format(h)
  42.                 os.makedirs(outpath,exist_ok=True)
  43.                 mail = mailparser.parse_from_string(data)
  44.                 with open("mail.txt","w",encoding="utf-8") as outfile:
  45.                     outfile.write("filename:{}\n".format(f)))
  46.                     outfile.write("\n".join(mail.text_plain))
  47.                 write_attachments(mail.attachments,outpath)
  48.         except Exception as e:
  49.             print(e)
  50.             print(traceback.format_exc())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement