如何正确配置 Flask Mail

How to configure Flask Mail properly

我正在尝试关注 this tutorial。当我尝试提交应该触发电子邮件的联系表格时,我收到内部服务器错误。错误日志显示:

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

说明上说要使用 from flask.ext.mail 导入,但我看到现在可能是 from flask_mail。我也试过将邮件端口从 465 更改为 587。这些更改都没有解决问题。我最新的代码是:

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)

您在配置初始应用后创建了第二个应用(可能是意外)。现在 "first" app 已配置并注册了分机,但 "second" app 用于注册路由并调用 .run().

删除 mail.init_app(app) 之后的行,第二个 app = Flask(__name__) 创建另一个应用程序。