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

3

我使用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个回答

3

只需打开文件并存储原始文本。如果审阅者接受它,只需转发文本。

而不是:

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

请您完成最后一部分代码,以便实际发送保存的电子邮件。如果我添加smtpObj = smtplib.SMTP('my.smtp.net') smtpObj.sendmail(sender, receiver, msg.as_string()) smtpObj.quit(),则我收到的电子邮件会有两个附加图像,而其他附加文件是ATT00001.txt和AT00002.htm。 - sprogissd
修复了电子邮件发送。 - Adriano Martins
谢谢。有没有办法不提交“发送者”和“接收者”的值,而是从保存的电子邮件中自动获取它们? - sprogissd
这种方法需要一些技巧,我现在无法实现。如果答案正确,请将其标记为正确并点赞。 - Adriano Martins

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接