Skip to main content
 首页 » 编程设计

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

2024年09月07日42lidabo

我使用 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() 

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

请您参考如下方法:

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

代替:

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