Python:如何将使用MIME生成的电子邮件保存到磁盘

时间:2018-03-22 01:58:49

标签: python python-2.7

我使用HTML模板创建电子邮件,并将图像附加到每封电子邮件中。在发送电子邮件之前,我想首先将它们保存在磁盘上进行审核,然后使用单独的脚本将已保存的电子邮件发送出去。目前,我通过以下方式生成和发送电子邮件。

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'] = 'sender@email.com'
msg['To'] = 'receiver@email.com'
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()

如何将完全相同的电子邮件保存到磁盘而不是立即发送?

1 个答案:

答案 0 :(得分:2)

只需打开文件并存储原始文本即可。如果审稿人接受了,只需转发文本。

而不是:

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

保存:

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

稍后,每当评论者接受文本时:

# 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()