1

好的,我正在使用 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
4

0 回答 0