Python -- Send Email When Exception Is Raised?

python send email
python send email with attachment
python send email without smtp server
python send anonymous email
python send encrypted email
python print exception message
python catch all exceptions
code to send email

I have a python class with many methods():

Method1()

Method2()

...........

...........

MethodN()

All methods -- while performing different tasks -- have the same scheme:

do something
do something else
has anything gone wrong?
    raise an exception

I want to be able to get an email whenever an exception is raised anywhere in the class.

Is there some easy way to combine this logic into the class, rather than calling SendEmail() before every raise Exception statement? what is the right, pythonic way to deal with such a case? canh a 'generalized' Exception handler be the solution? I'd be glad for any ideas you may have.

Note: Although this is a simple, obvious solution to the problem as stated, the below answer is probably better in most cases.

If the alternative is this:

if problem_test():
    SendEmail()
    raise Exception

Then why don't you just define a custom raise_email method?

def raise_email(self, e):
    SendEmail()
    raise e

Email Exception Handling in Python, In this article, we show how to handle email exception errors in Python. When sending emails in Python, there are a number of things that you must do, There is SMTPServerDisconnected error, which is an error that is raised when the server  email.errors: Exception and Defect classes¶ The following exception classes are defined in the email.errors module: exception email.errors.MessageError¶ This is the base class for all exceptions that the email package can raise. It is derived from the standard Exception class and defines no additional methods. exception email.errors

like @User said before Python has logging.handlers.SMTPHandler to send logged error message. Use logging module! Overriding exception class to send an email is a bad idea.

Quick example:

import logging
import logging.handlers

smtp_handler = logging.handlers.SMTPHandler(mailhost=("smtp.example.com", 25),
                                            fromaddr="from@example.com", 
                                            toaddrs="to@example.com",
                                            subject=u"AppName error!")


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

try:
  break
except Exception as e:
  logger.exception('Unhandled Exception')

8. Errors and Exceptions, It can also be used to print an error message and then re-raise the exception (​allowing a Attributes: expression -- input expression in which the error occurred​  In Python 3 there are 4 different syntaxes of raising exceptions. raise exception – No argument print system default message; raise exception (args)– with an argument to be printed; raise – without any arguments re-raises the last exception; raise exception (args) from original_exception – contain the details of the original exception

Python stdlib has dedicated class to do what you want. See logging.handlers.SMTPHandler

smtplib — SMTP protocol client, This exception is raised when the server unexpectedly disconnects, or when an attempt is made to use the SMTP instance before connecting it to a server. Note: When an exception is raised in Python, it is done with a traceback. The traceback gives you all the relevant information to be able to determine why the exception was raised and what caused it. Learning how to read a Python traceback and understanding what it is telling you is crucial to improving as a Python programmer.

Beware the wizard's apprentice!

It would be better to log those errors, then check to see when the last email was sent, and if the timespan is too short, do not send another message because the human being will already be looking at the log file. For many things, one message per day would be enough, but even for system critical things, if you have already had one failure, what could go wrong if you wait two hours to send the next email?

If you send one email per two hour timespan, then the maximum number of emails per day is 12. And if you get a cascading failure (you will!) then it will most likely happen within a couple of hours of the first failure event.

Most large networking companies offer an SLA of 4 hour to fix a failure, measured from the time it first occurs (because cascading failures tend to repeat) until the customer is satisified that it is fixed. If you have a tighter SLA than that, then unless it is some finance industry service, you probably are offering too high of a service level.

But if you do have a 4 hour SLA, then I would make sure that any email sent within 2 - 4 hours of the last email, should use whatever bells and whistles you can to prioritise it, highlight it, etc. For instance use the X-Priority header and put the word URGENT in the subject so that your mail client can display it in large bold red letters.

How do I stop a program when an exception is raised in Python , This is the base class for all exceptions that the email package can raise. Raised when a payload is added to a Message object using add_payload() , but the  An expression is tested, and if the result comes up false, an exception is raised. Assertions are carried out by the assert statement, the newest keyword to Python, introduced in version 1.5. Programmers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output.

Gist Link

The most important trick is here if secure parameter is not passed, the default value is None which raises exception if you are trying to authenticate with TLS/SSL enabled STMP Servers lik Gmail's, Yahoo's, Yandex's, STMP servers.

We passed an empty tuple to trigger smtp.ehlo() to authenticate correctly with SSL.

...
if self.secure is not None:
    smtp.ehlo()
    smtp.starttls(*self.secure)
    smtp.ehlo()
...


import logging
import logging.handlers

__author__ = 'Ahmed Şeref GÜNEYSU'


def foo():
    raise Exception("Foo Bar")


def main():
    logger = logging.getLogger()
    logger.addHandler(logging.handlers.SMTPHandler(
        mailhost=("smtp.mail.yahoo.com", 587),
        fromaddr="boss@example.com",
        toaddrs="me@example.com",
        subject="EXCEPTION",
        credentials=('smtpuser@example.com', 'MY SECRET PASSWORD'),
        secure=()))
    try:
        foo()
    except Exception, e:
        logging.exception(e)


if __name__ == '__main__':
    main()

Python Raise an Exception, Syntax of exception handling in python goes something like this: [code]try: .{​execute the code/functionality}. except(Exception, e): .{execute the code when​  Actually, I cannot even make sense with what the documentations says - if an exception is raised and caught by the task awaiting on gather, I would not even be able to get the returned results (even if the other task would, somehow, get done). Am I missing anything, or is there a problem with the documentation? This was tested with Python 3.7.2.

Python - Exceptions Handling, Web Application Development and Deployment with Python Daniel Rubio SUCCESS('Successfully sent email to "%s"' % email)) raise Exception except help <task_file_name> or python manage.py <task_file_name> --help Django  You can re-raise an exception caught in an exception handler and have another handler up the call stack handle it by using an empty raise statement inside the except block: except ValueError: raise # re raises the previous exception This way, the outer handler in 'main' can catch it and continue.

What Is an Exception? (The Java™ Tutorials > Essential Classes , When we raise exception, we let caller know upfront that input values are not to get an exception rather than a return value, which is the Python style to indicate that user, password, email, message): """send email to specific email address. Email Exception Handling in Python In this article, we show how to handle email exception errors in Python. When sending emails in Python, there are a number of things that you must do, including connecting to the email host such gmail.

18.1.8. email.errors: Exception and Defect classes, Raising an Exception. We can use raise to throw an exception if a condition occurs. The statement can be complemented with a custom exception. Illustration​  Update: I just noticed that the application didn't actually crash, everything still works fine, but I still think this should be handled by the websockets module so it doesn't print "socket.send() raised exception"/stack traces if a client has disconnected (or perhaps pass along the exceptions so they can be handled by applications using the

Comments
  • There are some exceptions that you don't need to catch, even in a global handler.
  • I think this is the best answer, but I would change the last line to: logger.exception ('Unhandled Exception')
  • This does not work for me. I use gmail, so I changed mailhost to 'smtp.gmail.com', and the fromaddr and toaddrs to two gmail addresses. I do not receive any email.
  • This is the best answer.
  • I got lost between 3 defs inside a class that is also inside a def. it might be that your solution is perfect, yet, is it a most to have such complexity?
  • It wraps the class in another class that checks to see if an attribute access is a method, and if so it wraps the method inside a function that catches any exception and sends an email in turn. It wraps them on the fly so that methods can be added later, instead of wrapping them when the class is built and missing any added after that.
  • By the way, you forgot to return the attribute when it's not a function. Right on the lines of "perils of unreadable code"