Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I email myself an error log from Flask?

Tags:

python

flask

How can I get Flask to send me an email if any 404 or 500 errors occur in the application? I inserted the following in my config.py which I came across here, but I don't receive any emails. I'm new to Flask so please excuse any mistakes.

from app import app

ADMINS = ['[email protected]']
if not app.debug:
    import logging
    from logging.handlers import SMTPHandler
    mail_handler = SMTPHandler('smtpout.secureserver.net',
                               '[email protected]',
                               ADMINS, 'YourApplication Failed',
                               credentials=('[email protected]','***'),
                               port=25)
    mail_handler.setLevel(logging.ERROR)
    app.logger.addHandler(mail_handler)

I'm also a bit confused by this line from the documentation:

If your mail server requires credentials, these can also be provided.

My server is not acting as a "mail server". What credentials should I be providing? My email is hosted at GoDaddy.

like image 488
kaoscify Avatar asked Dec 14 '15 19:12

kaoscify


People also ask

How do you send an error response in Flask?

Sometimes when building a Flask application, you might want to raise a HTTPException to signal to the user that something is wrong with the request. Fortunately, Flask comes with a handy abort() function that aborts a request with a HTTP error from werkzeug as desired.

How do I send an email from a Flask?

Step 1: Import the Mail and Message classes from the flask-mail module in the code. Step 3: Create an instance of the Mail class. Step 4: The Message object is set in a Python function that is mapped by the URL rule ('/').


1 Answers

You need to add the credentials for your email (username and password) like this:

mail_handler = SMTPHandler(mailhost=('smtpout.secureserver.net',25),
                           fromaddr='[email protected]',
                           toaddrs=ADMINS, subject='YourApplication Failed',
                           credentials=('mail_username','mail_password'))

In essence you need to login into your mail account (from godaddy) to be able to send emails. The IP used needs to be the IP provided by godaddy for the STMP service (I believe it is smtpout.secureserver.net) and the port without SSL is one of 25, 80, 3535 if you are using SSL the port is 465.

Hope it helps!

EDIT: Since it still doesn't work when it should I'm adding a full minimal source code to test it, this is the quickstart minimal hello word example modified to send emails when an error occurs and to always fail (it will send an email every time you access the page), fully tested on godaddy (us):

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    raise Exception
    #return 'Hello World!'

if __name__ == '__main__':
    ADMINS = ['[email protected]']
    if not app.debug:
        import logging
        from logging.handlers import SMTPHandler
        mail_handler = SMTPHandler(mailhost=('smtpout.secureserver.net',25),
                           fromaddr='[email protected]',
                           toaddrs=ADMINS, subject='YourApplication Failed',
                           credentials=('[email protected]','mypassword'))
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)
    app.run()

It is important tho that you need to check the actual smtp server you need to use. When you log into godaddy click the email admin button (the button on email workspace) there go to the top menu TOOLS -> SERVER FUNCTIONS . After that select your domain and in the last row (SMTP) you should see a domain like the one I provided for the smtp outgoing access, in my case I have different ones for different domains:

smtpout.asia.secureserver.net
smtpout.secureserver.net

Find the one you need to use and modify my sample code, you should receive the emails instantly on the web interface of your godaddy email.

Once you have the right server and use your credentials you should receive an email like this one when running the app:

Exception on / [GET]
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "hello.py", line 6, in hello_world
raise Exception
Exception
like image 121
Sergio Ayestarán Avatar answered Oct 13 '22 08:10

Sergio Ayestarán