Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to save emails generated with MIME to disk

I create emails using an HTML template, and I attach an image to each email. Before sending my emails out I would like to first save them on a disk for a review and then have a separate script to send the saved emails out. Currently, I generate and send emails the following way.

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.MIMEImage import MIMEImage
from email.MIMEBase import MIMEBase
from email import Encoders

fileLocation = 'C:\MyDocuments\myImage.png' 
attachedFile = "'attachment; filename=" + fileLocation
text = myhtmltemplate.format(**locals())

msg = MIMEMultipart('related')
msg['Subject'] = "My subject" 
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg.preamble = 'This is a multi-part message in MIME format.'

msgAlternative = MIMEMultipart('alternative')
msg.attach(msgAlternative)

part = MIMEBase('application', "octet-stream")
part.set_payload(open(fileLocation, "rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', attachedFile)
msg.attach(part)

msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)
msgText = MIMEText(text, 'html')
msgAlternative.attach(msgText)

fp = open(fileLocation, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()

# Define the image's ID
msgImage.add_header('Content-ID', '<image1>')
msg.attach(msgImage)

smtpObj = smtplib.SMTP('my.smtp.net')
smtpObj.sendmail(sender, receiver, msg.as_string())
smtpObj.quit()

How can I save exactly the same emails to a disk instead of sending them right away?

like image 388
sprogissd Avatar asked May 09 '26 15:05

sprogissd


1 Answers

Just open a file and store the raw text. If the reviewer accepts it, just forward the text.

Instead of:

smtpObj = smtplib.SMTP('my.smtp.net')
smtpObj.sendmail(sender, receiver, msg.as_string())
smtpObj.quit()

Makes it save:

f = open("output_file.txt", "w+")
f.write(msg.as_string())
f.close()

Later on, whenever the reviewer accepts the text:

# Read the file content
f = open("output_file.txt", "r")
email_content = f.read()
f.close()
# Send the e-mail
smtpObj = smtplib.SMTP('my.smtp.net')
smtpObj.sendmail(sender, receiver, email_content )
smtpObj.quit()
like image 102
Adriano Martins Avatar answered May 12 '26 06:05

Adriano Martins