Remove some images from a mail message
Jason Friedman
jsf80238 at gmail.com
Tue Apr 23 08:17:00 EDT 2013
This seemed to work.
#!/usr/bin/env python3
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.iterators import typed_subpart_iterator
from email.generator import Generator, BytesGenerator
import email.iterators
import os
import sys
import tempfile
IGNORE_SET = set((588, 1279, 1275, 1576, 1272, 1591,))
IMAGE = "image"
TEXT = "text"
PLAIN = "plain"
SUBJECT = "Subject"
FROM = "From"
TO = "To"
DATE = "Date"
WRITE_BINARY = "wb"
READ_BINARY = "rb"
output_message_file_name = "/home/jason/resulting_message"
input_file_name = "/home/jason/example_message"
with open(input_file_name, READ_BINARY) as reader:
message_in = email.message_from_binary_file(reader)
message_out = MIMEMultipart()
header_field_list = (SUBJECT, FROM, DATE)
for field_name in header_field_list:
message_out.__setitem__(field_name, message_in[field_name])
message_out[TO] = "jason"
temp_dir = tempfile.TemporaryDirectory()
for part in typed_subpart_iterator(message_in, maintype=IMAGE):
file_name = part.get_filename()
full_path = os.path.join(temp_dir.name, file_name)
with open(full_path, WRITE_BINARY) as writer:
writer.write(part.get_payload(decode=True))
if os.stat(full_path).st_size not in IGNORE_SET:
with open(full_path, READ_BINARY) as reader:
attachment = MIMEImage(reader.read())
message_out.attach(attachment)
for part in email.iterators.typed_subpart_iterator(message_in,
maintype=TEXT, subtype=PLAIN):
message_out.attach(part)
with open(output_message_file_name, WRITE_BINARY) as writer:
x = BytesGenerator(writer)
x.flatten(message_out)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130423/46e759a1/attachment.html>
More information about the Python-list
mailing list