Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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__)
app.config.update(
    MAIL_SERVER='[email protected]',
    MAIL_PORT=587,
    MAIL_USE_SSL=True,
    MAIL_USERNAME = 'ri******[email protected]',
    MAIL_PASSWORD = 'Ma*****fe'
)

mail = Mail(app)

@app.route('/send-mail/')
def send_mail():
    msg = mail.send_message(
        'Send Mail tutorial!',
        sender='ri******[email protected]',
        recipients=['ri*********[email protected]'],
        body="Congratulations you've succeeded!"
    )
    return 'Mail sent'
like image 554
stevenperry94 Avatar asked May 05 '16 19:05

stevenperry94


People also ask

How do I add mailing feature to flask application?

Step 1 − Import Mail and Message class from flask-mail module in the code. Step 2 − Then Flask-Mail is configured as per following settings. Step 3 − Create an instance of Mail class. Step 4 − Set up a Message object in a Python function mapped by URL rule ('/').

Can I use Gmail for SMTP relay?

On your device or in your app, connect to smtp-relay.gmail.com on one of these ports: 25, 465, or 587.


1 Answers

  1. The server is "smtp.gmail.com".
  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. This may also require enabling 2-step verification. You should probably set this up anyway.
MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT = 465
MAIL_USE_SSL = True
MAIL_USERNAME = '[email protected]'
MAIL_PASSWORD = 'app password generated in step 3'
like image 68
davidism Avatar answered Sep 20 '22 15:09

davidism