pythonpython-loggingmime-mail

How to send an error message being printed in an exception case by email to a user?


I am using Python3.7 I am trying to email an error in the except condition to the user if the code is not working and following is my code:

except Exception as e:
logging.basicConfig(filename='logfile.log',format='%(asctime)s %(message)s',filemode='w')

logger=logging.getLogger()

logger.setLevel(logging.ERROR)

logger.error(e)
print("ERROR MESSAGE",e)

MY_ADDRESS = '*****@gmail.com'
PASSWORD = '*******'
MY_ADDRESS1 = '****@gmail.com'

s = smtplib.SMTP(host='smtp.gmail.com', port=***)
s.starttls()
s.login(MY_ADDRESS, PASSWORD)
print("login")
msg = MIMEMultipart()       # create a message

msg['From']=MY_ADDRESS
msg['To']=MY_ADDRESS1
msg['Subject']="ERROR MESSAGE"

message="ERROR"
msg.attach.as_string(MIMEText(e))
print("ERROR MAILED")

s.send_message(msg)
s.quit()

I want to send the error message in variable 'e' which is being printed

But I am unable to do so Following is the error:

This is the error which i want to print and mail:

ERROR MESSAGE [Errno 2] No such file or directory: 'C:\\Python37\\Processed\\Invoice.xlsx'

This is the error shown on the python shell:

Traceback (most recent call last):
  File "C:\Python37\Sopan.py", line 30, in <module>
    wb.save(workbook_name)
  File "C:\Python37\lib\site-packages\openpyxl\workbook\workbook.py", line 408, in save
    save_workbook(self, filename)
  File "C:\Python37\lib\site-packages\openpyxl\writer\excel.py", line 291, in save_workbook
    archive = ZipFile(filename, 'w', ZIP_DEFLATED, allowZip64=True)
  File "C:\Python37\lib\zipfile.py", line 1207, in __init__
    self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Python37\\Processed\\Invoice.xlsx'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python37\Sopan.py", line 88, in <module>
    msg.attach.as_string(MIMEText(e))
AttributeError: 'function' object has no attribute 'as_string'
During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python37\Sopan.py", line 88, in <module>
    msg.attach.as_string(MIMEText(e))
AttributeError: 'function' object has no attribute 'as_string'

How do i send the error message being printed in variable 'e' by email to someone

THANK YOU


Solution

  • The logging module itself has smtp handler you can do something like this:

    import logging
    import logging.handlers
    
    smtp_handler = logging.handlers.SMTPHandler(mailhost=("smtp.example.com", 25),
                                                fromaddr="someone@something.com", 
                                                toaddrs="receiver@mail.com",
                                                subject=u"ERROR IN YOURAPP!")
    
    
    logger = logging.getLogger()
    logger.addHandler(smtp_handler)
    
    try:
      raise Exception
    except Exception as e:
      logger.exception('Unhandled Exception')
    

    for more info see doc