Flask-Mail调用send报缺少message参数TypeError问题求助
报错根因
你遇到的TypeError: _MailMixin.send() missing 1 required positional argument: 'message'是错误调用flask-mail发送方法导致的:
你在Init.py中初始化了绑定当前Flask app的Mail实例mail = Mail(app),但在views.py中调用发送方法时,直接使用Mail类本身执行Mail.send(msg),而非初始化完成的实例。类直接调用实例方法时,不会自动绑定self参数,会把你传入的msg当做self参数解析,因此提示缺少必填的message参数。
另外你的代码中还存在一处变量名错误:生成重置链接时使用了未定义的my_user.email,你实际查询到的用户对象变量名为user,运行到这行也会抛出异常。
修复方法
- 先在views.py中正确导入你在Init.py中初始化好的mail实例,不要只导入Mail类,导入路径按照你项目的实际结构调整即可,参考写法:
# 相对导入示例,适配Init.py在同项目包下的场景 from . import mail
- 修正发送邮件的调用语句,把类调用改为实例调用,同时修正链接生成处的变量名错误,修正后的对应代码段如下:
if request.method =="POST": user = User.query.filter_by(email = form.email.data).first() if user: #generate new token token = str(uuid4()).replace('-','') #update user token in db user.token = token db.session.add(user) db.session.commit() link = 'http://' + getenv('DOMAIN') + url_for( 'update_password', email=user.email, token=token) # 修正未定义的my_user变量为user msg = Message('Password Reset Request', sender='noreply@demo.com', recipients=[user.email]) msg.body = 'To reset your password, visit the following link: ' + link + '. If you did not make this request then simply ignore this email and no changes will be made.' mail.send(msg) # 修正类调用为初始化完成的mail实例调用 flash('We have sent an email to change your password. Please check your Spam folder if not found.', category = 'success') return redirect(url_for('auth.login'))
注意:确保导入的是已经绑定app配置的mail实例,不要在views.py中重新实例化未加载配置的Mail对象,否则会出现邮件配置不生效的问题。
内容的提问来源于stack exchange,提问作者bertcool
相关产品推荐
相关产品推荐

