如何正确配置Flask Mail

时间:2015-01-05 11:04:23

标签: python flask flask-mail

我正在尝试关注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)

1 个答案:

答案 0 :(得分:2)

在配置初始应用程序后,您创建了第二个应用程序(可能是偶然的)。现在配置了“第一个”app并注册了扩展名,但“第二个”app用于注册路由并调用.run()

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