I would like to parse (serialize) a multipart email (or any and all types with multiple email attachments having inline images, attachments etc), set its body content-type with some extra information and re-generate the email before sending it out. How can this be achieved with the most simplest python code? Using python version 3.6. Right now I am using email.walk() and getting the first available text/plain, text/html and assume its the body of the covering mail, Further parsing recursively thru' the different parts of the mail by walk()...this seems cumbersome. Any easy method? Adding a code snippet what I am trying: #!/usr/bin/python3 """ USAGE: From commandline: cat mail | python warning_mail_stdout.py
This script reads mail from stdin and appends mail body with the "warning" and prints out the appended mail on to stdout """
import imaplib
import email
import logging
import smtplib
import re
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# from subprocess import Popen, PIPE
import sys
import email, os
title = ''
logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
from email.policy import default
from email import policy
from email.parser import BytesParser
from email.mime.message import MIMEMessage
parser = email.parser.Parser()
def login():
# Read message from Std Input
mail = BytesParser(policy=policy.default).parse(open('1email_sample.eml','rb'))
if mail is None:
print("No mail in stdin ...")
else:
#mail is not None:
mbody = ''
mhtml = ''
text_body = ''
mail_charset = None
html_body = ''
mail_from = email.utils.parseaddr(mail['From'])[1]
mwarn = ''
new_message = ''
attached_bool = False
mail_attached_bool = False
h=p=related_body=None
h_body=plain_body = None
new_message1 = email.message.EmailMessage()#policy=default)
warning_txt = "[Caution: This message came from an external domain.]"
new_message = email.message.EmailMessage()
# copying header values
for header_val in mail:
parser.parsestr(header_val)
new_message[header_val] = mail[header_val]
print(new_message[header_val])
mailbody = mail.get_body(preferencelist=('related', 'html', 'plain'))
new_message1.attach(mailbody)
new_message.set_type('multipart/related')
new_message.attach(new_message1)
for p in mail.iter_attachments():
if p.is_attachment():
new_message.attach(p)
recipients = [
"sha73@yahoo.com",
]
# s ---is the smtp server to send out mail
#'''
try:
print(new_message.get_content_type(), 'vvvvv sent')
s.sendmail(mail_from, recipients,bytes(new_message))
except UnicodeEncodeError:
s.sendmail(mail_from, recipients,
new_message.as_string().encode("utf-8"))
#'''
s.close()
if __name__ == "__main__":
login()