Flask 邮件和 GMail 设置 - 非常困惑

Flask Mail & GMail Settings - Very Confused

我一直在学习 Flask(在许多非常慷慨的 YouTuber 的帮助下)
我认为添加一个通过 GMail 发送电子邮件通知的 'Subscribe' 函数会相当简单。
经过几天的谷歌搜索后,我从端口 465 或 587、SSL and/or TLS enabled/disabled 的每个组合中得到以下结果。 允许 Gmail 中安全性较低的应用程序选项。

from flask import Flask  
from flask_mail import Mail, Message

app = Flask(__name__)

app.config['MAIL_DEBUG'] = True  
app.config['TESTING'] = False  
app.config['MAIL_SERVER'] = 'smtp.gmail.com'  
app.config['MAIL_PORT'] = see results below  
app.config['MAIL_USE_TLS'] = see results below  
app.config['MAIL_USE_SSL'] = see results below  
app.config['MAIL_USERNAME'] = None  
app.config['MAIL_PASSWORD'] = 'secret_password'  
app.config['MAIL_DEFAULT_SENDER'] = 'me@gmail.com'  
app.config['MAIL_MAX_EMAILS'] = None  
app.config['MAIL_SUPPRESS_SEND'] = False  
app.config['MAIL_ASCII_ATTACHMENTS'] = False  

mail = Mail(app)

@app.route('/')  
def home():  
    msg = Message('Test Message from Flask Mail', recipients=['you@gmail.com'])  
    mail.send(msg)  
    return 'OK'

if __name__ == '__main__':  
    app.run(debug=True)

结果 -

Port    SSL TLS Result  
465 On  On  smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server  
465 Off On  smtplib.SMTPServerDisconnected: Connection unexpectedly closed  
465 On  Off smtplib.SMTPSenderRefused: (530, b'5.7.0 Authentication Required  
465 Off Off smtplib.SMTPServerDisconnected: Connection unexpectedly closed  
            
587 On  On  ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number  
587 Off On  smtplib.SMTPSenderRefused: (530, b'5.7.0 Authentication Required  
587 On  Off ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number  
587 Off Off smtplib.SMTPSenderRefused: (530, b'5.7.0 Must issue a STARTTLS command first  

SSL 版本为 -

import ssl
ssl.OPENSSL_VERSION
'OpenSSL 1.1.1f 31 Mar 2020'

这个 SMTPLIB 工作得很好 -

import smtplib

smtp_server = 'smtp.gmail.com'  
port = 587  
sender = 'me@gmail.com'  
password = 'secret'  
receiver = 'you@gmail.com'  
msg = "Test Message from SMTPLIB"  

server = smtplib.SMTP(smtp_server, port)  
server.starttls()  
server.login(sender,password)  
server.sendmail(sender, receiver, msg)  

现在已经有几年了,但对我有用(查看旧代码)是

app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False
app.config['MAIL_USERNAME'] = <your email address> # should not be None as you currently have in your code

注意:我只使用此代码在我的本地机器上进行测试。我切换到 Google App Engine 邮件,后来切换到 SendGrid