Sending e-mails on the occurrence of errors
It is a good idea to receive errors when something unexpected happens with the application. Setting this up is pretty easy and adds a lot of convenience to the process of error handling.
Getting ready
We will take the application from the last recipe and add mail_handler to it to make our application send e-mails when an error occurs. Also, we will demonstrate how to set up these e-mails using Gmail as the SMTP server.
How to do it…
We will first add the handler to our configuration in __init__.py. This is similar to how we added file_handler in the last recipe:
RECEPIENTS = ['some_receiver@gmail.com']
if not app.debug:
import logging
from logging import FileHandler, Formatter
from logging.handlers import SMTPHandler
file_handler = FileHandler(app.config['LOG_FILE'])
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
mail_handler = SMTPHandler(
("smtp.gmail.com", 587), 'sender@gmail.com', RECEPIENTS...