stevenperry94 stevenperry94 - 1 year ago 195
Python Question

Configure Flask-Mail to use GMail

When I try to send an email using Flask-Mail to Gmail's SMTP server using the settings below, I get

[Errno -2] Name or service not known
. How do I fix my configuration to send email with Gmail?

from flask import Flask, render_template, redirect, url_for
from flask_mail import Mail, Message

app = Flask(__name__)
MAIL_SERVER='[email protected]',
MAIL_USERNAME = 'ri******[email protected]',
MAIL_PASSWORD = 'Ma*****fe'

mail = Mail(app)

def send_mail():
msg = mail.send_message(
'Send Mail tutorial!',
sender='[email protected]',
recipients=['[email protected]'],
body="Congratulations you've succeeded!"
return 'Mail sent'

Answer Source
  1. The server is "".
  2. The port must match the type of security used.
    • If using STARTTLS with MAIL_USE_TLS = True, then use MAIL_PORT = 587.
    • If using SSL/TLS directly with MAIL_USE_SSL = True, then use MAIL_PORT = 465.
    • Enable either STARTTLS or SSL/TLS, not both.
  3. Depending on your Google account's security settings, you may need to generate and use an app password rather than the account password. You should probably set this up anyway.
MAIL_USERNAME = '[email protected]'
MAIL_PASSWORD = 'app password generated in step 3'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download