python email exception code example

Example: python email exception error

#This gives feedback on errors within a script which then emails output

import win32com.client
import os
import sys

try:
  #Some code
  
except Exception as e:
    exc_type, exc_obj, exc_tb = sys.exc_info()
    fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
    print((exc_type, fname, exc_tb.tb_lineno, str(e)))
    error_line  = str(exc_type) + '  ' + str(fname) + '  Line: ' + str(exc_tb.tb_lineno) + '  ' + str(e)
    
    olMailItem = 0x0
    obj = win32com.client.GetActiveObject("Outlook.Application")
    newMail = obj.CreateItem(olMailItem)
    newMail.Subject = "There's a snake in my boot!"
    newMail.HTMLBody = """Morning
                      <br>
                      <br>Your script failed!
                      <br>
                      <br>{}#Script name
                      <br>{}#Line number where failed
                      <br>{}#Error goes here
                      <br>
                      <br>Kind regards""".format('Script: '+str(fname),'Line: '+str(exc_tb.tb_lineno),'Error: '+ str(e))
    newMail.To = "[email protected]"
    newMail.Send()