Flask 发送QQ邮箱邮件,遇到的各种问题解决

先上测试成功代码

以下代码在2019年1月28日 python 3.6下运行收到邮件

from flask import Flask
from flask_mail import Mail, Message

app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = "[email protected]"
app.config['MAIL_PASSWORD'] = "oxdjfsuyvcwxxxx"         # 后几位被我用xxxx代替,非真实可用的
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail = Mail(app)
with app.app_context():
    message = Message(subject='hello flask-mail', sender="[email protected]", recipients=['[email protected]'], body='测试邮件')
    mail.send(message)

遇到的问题

一,smtplib.SMTPAuthenticationError: (535
原因:使用的是QQ邮箱登录密码,实际并不是登录密码
解决:QQ邮箱需要开启服务
按下图中开启,开启会得到个密码,填写在配置中
app.config[‘MAIL_PASSWORD’] = “oxdjfsuyvcwxxxx”

另外只需要发送邮箱的账号开启服务就可以,接收的邮件不需要
在这里插入图片描述
二,TypeError: can only concatenate list (not “str”) to list
原因:message = Message(subject='hello flask-mail', sender="[email protected]", recipients='[email protected]', body='测试邮件')
recipients中要使用list格式
解决:message = Message(subject='hello flask-mail', sender="[email protected]", recipients=['[email protected]'], body='测试邮件')

三,ConnectionRefusedError: [WinError 10061] 由于目标计算机积极拒绝,无法连接。
原因:
在这里插入图片描述
mail = Mail(app) 需要放在所有app.config后面,不然配置不会生效
解决:
参考验证通过代码

四,RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context(). See the
documentation for more information.
原因: 没有使用with app.app_context()
在这里插入图片描述
解决:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/lhh08hasee/article/details/86687131