简体   繁体   English

如何正确配置Flask Mail

[英]How to configure Flask Mail properly

I am trying to follow this tutorial . 我正在尝试按照本教程进行操作 When I try to submit the contact form, which should trigger the email, I get an internal server error. 当我尝试提交联系表单时,该表单会触发电子邮件,但出现内部服务器错误。 The error log says: 错误日志显示:

RuntimeError: The curent application was not configured with Flask-Mail

The instructions say to use from flask.ext.mail to import but I've seen that it might be from flask_mail now. 说明说要使用from flask.ext.mail进行导入,但是我已经看到它现在可能from flask_mail I've also tried changing the mail port from 465 to 587. Neither of these changes have been fixed the problem. 我也尝试将邮件端口从465更改为587。这些更改均未解决问题。 My most up to date code is: 我最新的代码是:

from flask import Flask, render_template, request, flash
from forms import ContactForm
from flask_mail import Mail, Message

mail = Mail()

app = Flask(__name__)

app.secret_key = 'development key'

app.config["MAIL_SERVER"] = "smtp.gmail.com"
app.config["MAIL_PORT"] = 587
app.config["MAIL_USE_SSL"] = True
app.config["MAIL_USERNAME"] = 'contact_email@gmail.com'  ## CHANGE THIS
app.config["MAIL_PASSWORD"] = 'password'

mail.init_app(app)

app = Flask(__name__)
app.secret_key = 'Oh Wow This Is A Super Secret Development Key'


@app.route('/')
def home():
  return render_template('home.html')

@app.route('/about')
def about():
  return render_template('about.html')

@app.route('/contact', methods=['GET', 'POST'])
def contact():
  form = ContactForm()

  if request.method == 'POST':
    if form.validate() == False:
      flash('All fields are required.')
      return render_template('contact.html', form=form)
    else:
      msg = Message(form.subject.data, sender='contact_email@gmail.com', recipients=['recipient@gmail.com'])
      msg.body = """
      From: %s <%s>
      %s
      """ % (form.name.data, form.email.data, form.message.data)
      mail.send(msg)

      return render_template('contact.html', success=True)

  elif request.method == 'GET':
    return render_template('contact.html', form=form)

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

You created a second app (presumably by accident) after configuring the initial app. 配置初始应用程序后,您创建了第二个应用程序(可能是偶然的)。 Right now the "first" app is configured and has the extension registered, but the "second" app is used to register the routes and call .run() . 现在,“第一个” app已配置并已注册扩展名,但“第二个” app用于注册路线并调用.run()

Remove the line after mail.init_app(app) , the second app = Flask(__name__) that creates another app. 删除mail.init_app(app)之后的行,第二个app = Flask(__name__) ,它创建另一个应用程序。

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

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