Configure Flask-Mail to use GMail

走远了吗. 提交于 2019-11-27 01:24:02

问题


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='smtp@gmail.com',
    MAIL_PORT=587,
    MAIL_USE_SSL=True,
    MAIL_USERNAME = 'ri******a@gmail.com',
    MAIL_PASSWORD = 'Ma*****fe'
)

mail = Mail(app)

@app.route('/send-mail/')
def send_mail():
    msg = mail.send_message(
        'Send Mail tutorial!',
        sender='ri******a@gmail.com',
        recipients=['ri*********07@msn.com'],
        body="Congratulations you've succeeded!"
    )
    return 'Mail sent'

回答1:


  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 = 'username@gmail.com'
MAIL_PASSWORD = 'app password generated in step 3'



回答2:


A small but important addition to davidism's answer:

You must have '2-step verification' enabled on your Google account before you're able to set up app-specific passwords.



来源:https://stackoverflow.com/questions/37058567/configure-flask-mail-to-use-gmail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!