2015-11-06 84 views
0

我的目標是保存我的腳本使用smtplib模塊發送的電子郵件。Python - 在使用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模塊的文檔,但找不到旋鈕來打印電子郵件的標題。

是否有任何黑客(如使用另一個模塊來監控流量等),我可以用它來保存我從腳本發送的電子郵件的方式?

回答

0

你可以得到包括使用str()頭整個電子郵件消息的字符串版本:

save_msg = str(msg) 
+0

酷..這就是我想要的。謝謝您的幫助。 – gixxer

相關問題