1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| import os import email from email import policy from email.parser import BytesParser
def save_attachments_from_eml(eml_file_path, output_dir, file_name): with open(eml_file_path, 'rb') as f: eml_content = f.read()
msg = BytesParser(policy=policy.default).parsebytes(eml_content) for part in msg.iter_attachments(): filename = part.get_filename() if filename: file_data = part.get_payload(decode=True) output_file_path = os.path.join(output_dir, file_name + '-' + filename) with open(output_file_path, 'wb') as f: f.write(file_data) print(f"Saved attachment: {output_file_path}")
eml_file_path = '/Users/wangmingjie/Desktop/NET' output_dir = '/Users/wangmingjie/Desktop/NET-attachment' os.makedirs(output_dir, exist_ok=True)
files = os.listdir(eml_file_path)
for file in files: if file.endswith('.eml'): file_name = file.split('.')[0] save_attachments_from_eml(os.path.join(eml_file_path, file), output_dir, file_name)
print('存储完成,共存储了{}个文件'.format(len(files)))
|