简体   繁体   English

Python-使用smtplib发送之前打印/保存电子邮件

[英]Python - print/save the email before sending using smtplib

My objective is to save the email that my script sends using smtplib module. 我的目标是使用smtplib模块保存脚本发送的电子邮件。

Here is how I am sending the email: 这是我发送电子邮件的方式:

#Creating a multipart body
msg = MIMEMultipart()
#Attaching files to the email
for file in tc['attachments']:
   try:
       part = email.mime.base.MIMEBase('application', "octet-stream")
       part.set_payload( open(file, "rb").read())
       email.encoders.encode_base64(part)
       part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
       msg.attach(part)
   except Exception as err:
       print "Exception when attaching file %s to the email: \n %s" % (file, err)
       print traceback.print_exc()

#Connecting to the SMTP server
smtp = smtplib.SMTP("1.2.3.4")

#Sending the email
try:
    status = smtp.sendmail(msg['From'], send_to, msg.as_string())
    print status
    smtp.close()
except Exception, e:
    print "Unable to send the email. Exception seen: %s" % e

Now, if I save msg.as_string() to a variable, it only saves the body of the email, but I want the whole email as it is sent. 现在,如果我将msg.as_string()保存到一个变量中,则它仅保存电子邮件的正文,但是我希望在发送整个电子邮件。

I looked into smtplib module's documentation but couldn't find a knob to print the headers of the email. 我查看了smtplib模块的文档,但找不到用于打印电子邮件标题的旋钮。

Is there any hack (like using another module to monitor the traffic, etc) that I can use to save the email the way I sent from the script? 是否可以使用从脚本发送方式保存电子邮件的任何黑客手段(例如使用其他模块监视流量等)?

您可以使用str()获得整个电子邮件的字符串版本,包括标题:

save_msg = str(msg)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM