我一直在尝试让我的 Flask 应用程序使用我的 Gmail 帐户发送电子邮件。
我在 .env 文件中尝试了以下配置:
MAIL_SERVER=smtp.gmail.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=special_gmail_password
MAIL_USE_TLS=False
MAIL_USE_SSL=True
和
MAIL_SERVER=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=special_gmail_password
MAIL_USE_TLS=True
MAIL_USE_SSL=False
并使用以下内容来设置我的配置:
app.config['MAIL_SERVER']= os.environ.get('MAIL_SERVER')
app.config['MAIL_PORT'] = os.environ.get('MAIL_PORT')
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
app.config['MAIL_USE_TLS'] = os.environ.get('MAIL_USE_TLS')
app.config['MAIL_USE_SSL'] = os.environ.get('MAIL_USE_SSL')
邮件代码:
def send_email(subject, sender, recipients, name, link, body):
msg = Message(subject=subject, sender=sender, recipients=recipients)
msg.html = render_template("email.html", name=name, link=link, content=body, user=current_user, recipient=recipients[0])
# Send the email
mail.send(msg)
mail = Mail(app)
第一个配置给出:
raise SMTPNotSupportedError(
smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server.
第二个配置给出:
ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:997)
我知道 PythonAnywhere 推荐 https://help.pythonanywhere.com/pages/SMTPForFreeUsers 上的第二种配置,但我无法让这个也正常工作。如何在 Pythonanywhere 中发送电子邮件?
要通过 Gmail 的 SMTP 服务器发送电子邮件,您可以使用以下配置:
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587 # Use port 587 for TLS
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False
此外,请务必确保您已允许安全性较低的应用程序访问您的 Gmail 帐户,因为 Gmail 的安全设置可能会阻止来自您的应用程序的连接。