5

When sending any message via Flask-Mail, such as below, the last line with mail.send(msg) will also result in the mail headers and content being logged.

Message("Hello", sender="from@example.com", recipients=["to@example.com"])
msg.body = 'anything'
mail.send(msg)

As my mail may contain sensitive information, I want to disable this logging entirely. Yet, playing around with the logging module, I could not find a logger configured for Flask-Mail.

How do I disable logging in Flask-Mail?

Felix
  • 332
  • 1
  • 9
  • I know that this question has accepted answer, but I had the same issue just now and I noticed that it is only when I have in my bash set env variable `FLASK_ENV=development` then the `app.extensions['mail'].debug` is `True`, when removing this env variable `FLASK_ENV` and leaving as it would be in production, then `app.extensions['mail'].debug` is `False`. With this in mind, I don't need to override the default functionality when initiating `Mail` class and in `development` environment I can debug it easier when it is turned on :) – simkusr Jan 09 '20 at 08:04

1 Answers1

13

Figured this one out:

Flask-Mail uses Python's smtplib to send mail. smtplib does not use the logging module, but it prints information for debugging to stderr.

smtplib includes following method:

def set_debuglevel(self, debuglevel):
    """Set the debug output level.

    A non-false value results in debug messages for connection and for all
    messages sent to and received from the server.

    """
    self.debuglevel = debuglevel

If we use Flask-Mail, we can set this variable when we initialize our app like this:

app = Flask(__name__)
mail = Mail(app)
app.extensions['mail'].debug = 0

Any output is now suppressed.

Felix
  • 332
  • 1
  • 9