【问题标题】:Python - print/save the email before sending using smtplibPython - 在使用 smtplib 发送之前打印/保存电子邮件
【发布时间】:2016-02-08 05:22:03
【问题描述】:

我的目标是保存我的脚本使用 smtplib 模块发送的电子邮件。

这是我发送电子邮件的方式:

#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

现在,如果我将msg.as_string() 保存到一个变量中,它只会保存电子邮件的正文,但我想要发送整个电子邮件。

我查看了smtplib 模块的文档,但找不到打印电子邮件标题的旋钮。

是否有任何 hack(比如使用另一个模块来监控流量等)可以用来保存我从脚本发送的电子邮件?

【问题讨论】:

    标签: python email smtp smtpclient smtplib


    【解决方案1】:

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

    save_msg = str(msg)
    

    【讨论】:

    • 酷..这就是我想要的。感谢您的帮助。
    猜你喜欢
    • 2017-08-13
    • 2021-04-26
    • 1970-01-01
    • 2014-01-31
    • 2017-09-20
    • 2023-02-11
    • 2011-02-12
    • 2018-12-09
    • 2015-09-07
    相关资源
    最近更新 更多