<div dir="ltr"><div>This seemed to work.</div><div><br></div><div>#!/usr/bin/env python3</div><div>from email.mime.image import MIMEImage</div><div>from email.mime.text import MIMEText</div><div>from email.mime.multipart import MIMEMultipart</div>
<div>from email.iterators import typed_subpart_iterator</div><div>from email.generator import Generator, BytesGenerator</div><div>import email.iterators</div><div>import os</div><div>import sys</div><div>import tempfile</div>
<div><br></div><div>IGNORE_SET = set((588, 1279, 1275, 1576, 1272, 1591,))</div><div>IMAGE = "image"</div><div>TEXT = "text"</div><div>PLAIN = "plain"</div><div>SUBJECT = "Subject"</div>
<div>FROM = "From"</div><div>TO = "To"</div><div>DATE = "Date"</div><div>WRITE_BINARY = "wb"</div><div>READ_BINARY = "rb"</div><div><br></div><div>output_message_file_name = "/home/jason/resulting_message"</div>
<div>input_file_name = "/home/jason/example_message"<br></div><div>with open(input_file_name, READ_BINARY) as reader:</div><div> message_in = email.message_from_binary_file(reader)</div><div><br></div><div>message_out = MIMEMultipart()</div>
<div>header_field_list = (SUBJECT, FROM, DATE)</div><div>for field_name in header_field_list:</div><div> message_out.__setitem__(field_name, message_in[field_name])</div><div>message_out[TO] = "jason"<br></div>
<div><br></div><div>temp_dir = tempfile.TemporaryDirectory()</div><div>for part in typed_subpart_iterator(message_in, maintype=IMAGE):</div><div> file_name = part.get_filename()</div><div> full_path = os.path.join(<a href="http://temp_dir.name">temp_dir.name</a>, file_name)</div>
<div> with open(full_path, WRITE_BINARY) as writer:</div><div> writer.write(part.get_payload(decode=True))</div><div> if os.stat(full_path).st_size not in IGNORE_SET:</div><div> with open(full_path, READ_BINARY) as reader:</div>
<div> attachment = MIMEImage(reader.read())</div><div> message_out.attach(attachment)</div><div><br></div><div>for part in email.iterators.typed_subpart_iterator(message_in, maintype=TEXT, subtype=PLAIN):</div>
<div> message_out.attach(part)</div><div><br></div><div>with open(output_message_file_name, WRITE_BINARY) as writer:</div><div> x = BytesGenerator(writer)</div><div> x.flatten(message_out)</div><div><br></div></div>