How to get message to my gmail if Python script raise exception

I have tried with logging.handlers ,but failed I took code from the web and i have tried it .

import logging
import logging.handlers

smtp_handler = logging.handlers.SMTPHandler(mailhost=("smtp.gmail.com", 587),
                                            fromaddr="name@gmail.com", 
                                            toaddrs="name@gmail.com",
                                            subject=u"AppName error!")


logger = logging.getLogger()
logger.addHandler(smtp_handler)

try:
    data= Data
except Exception as e:
    logger.exception('Unhandled Exception')

In my code i have used variable data and assigned it with Data which is not even defined hence it throws Exception. I want to get the Exception error to my gmail. How can i achieve it. If any answer would be appreciated.

1 answer

  • answered 2020-01-28 13:42 Green Cloak Guy

    Instead of figuring out how smtplib works, my approach was to install a mailserver on the machine and call that using os.popen:

    def sendmail_email(msg):
        sendmail_location = "/usr/sbin/sendmail"
        sendmail = os.popen("{} -t".format(sendmail_location), 'w')
        sendmail.write(msg)
        status = sendmail.close()
        print("Sent the following email with sendmail, status {}:".format(status))
        print(msg)
    
    ...
    except Exception as e:
        import traceback
        message = """To:your_address@domain.com
    From:your_program@domain.com
    Subject:An exception has occurred.
    
    Hello Father,
    
    An exception has occurred:
    
    {}
    
    Here is the stack trace for the exception:
    
    {}
    
    Thank you,
    -The Machine""".format(e.message, traceback.format_exc())
        sendmail_email(message)
    

    I got that solution from this website, which I found to be very helpful, though at this point it's somewhat out of date.