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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With