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=("", 587),
                                            subject=u"AppName error!")

logger = logging.getLogger()

    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')
        status = sendmail.close()
        print("Sent the following email with sendmail, status {}:".format(status))
    except Exception as e:
        import traceback
        message = """
    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())

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