好的,我正在使用Miguel Grinberg的Flask Mega教程(顺便说一句,这很棒!)作为基础。如果我在python解释器中运行它,它工作正常,但是当我在Web应用程序中提交表单时,我没有收到错误消息,但消息不发送。我的app.py下面的代码。提前谢谢!
from flask import Flask, render_template, request, flash
from forms import ContactForm
from flask_mail import Message, Mail
from packages.decorators import async
app = Flask(__name__)
app.secret_key = 'dummy_key'
app.config["MAIL SERVER"] = "mail.domainname.com"
app.config["MAIL_SUPPRESS_SEND"] = False
app.config["TESTING"] = False
app.config["MAIL_PORT"] = 26
app.config["MAIL_USE_TLS"] = False
app.config["MAIL_USE_SSL"] = False
app.config["MAIL_USERNAME"] = 'webmaster@domainname.com'
app.config["MAIL_PASSWORD"] = 'password'
mail = Mail(app)
@app.route('/')
def index():
return render_template("home.html")
@app.route('/<string:page_name>')
def static_page(page_name):
return render_template('%s.html' % page_name)
@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='webmaster@domainname.com', recipients=['admin@domainname.com'])
msg.body = """
From: %s %s <%s>
%s
""" % (form.firstName.data, form.lastName.data, form.email.data, form.comment.data)
@async
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
send_async_email(app, msg)
return 'Form posted.'
elif request.method == 'GET':
return render_template('contact.html', form=form)
if __name__ == '__main__':
app.run()
因此,在我提交表单后,我看到“表单已发布”,但从未收到电子邮件。我在解释器中做的唯一不同的是我用字符串手动填写msg变量而不是从表单字段接收输入。
编辑:下面是packages.decorators中的内容
from threading import Thread
def async(f):
def wrapper(*args, **kwargs):
thr = Thread(target=f, args=args, kwargs=kwargs)
thr.start()
return wrapper