简体   繁体   English

配置 Flask-Mail 以使用 GMail

[英]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 .当我尝试使用以下设置使用 Flask-Mail 向 Gmail 的 SMTP 服务器发送电子邮件时,我收到[Errno -2] Name or service not known How do I fix my configuration to send email with Gmail?如何修复我的配置以使用 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. The server is "smtp.gmail.com".服务器是“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 .如果将 STARTTLS 与MAIL_USE_TLS = True使用,则使用MAIL_PORT = 587
    • If using SSL/TLS directly with MAIL_USE_SSL = True , then use MAIL_PORT = 465 .如果直接将 SSL/TLS 与MAIL_USE_SSL = True使用,则使用MAIL_PORT = 465
    • Enable either STARTTLS or SSL/TLS, not both.启用 STARTTLS 或 SSL/TLS,不要同时启用。
  3. Depending on your Google account's security settings, you may need to generate and use an app password rather than the account password.根据您的 Google 帐户的安全设置,您可能需要生成和使用应用密码而不是帐户密码。 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'

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.您必须先在 Google 帐户上启用“两步验证”,然后才能设置应用专用密码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM