Disable logging in Flask-Mail when sending message

Viewed 1117

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?

1 Answers

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.

Related