Search code examples
pythonemailsmtpsmtpclientsmtplib

Python - print/save the email before sending using smtplib


My objective is to save the email that my script sends using smtplib module.

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.

I looked into smtplib module's documentation but couldn't find a knob to print the headers of the email.

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?


Solution

  • You can get a string version of the whole email message including headers using str():

    save_msg = str(msg)