Flask-Mail:空消息

Flask-Mail: empty messages

目前我正在尝试使用 flask、flask-mail 和 flask-WTF 创建联系页面。正在发送消息,但我只收到 "From: None None Random string"。你能告诉我,我做错了什么吗?

server.py:

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

mail = Mail()

app = Flask(__name__)
app.secret_key = 'developerKey'

app.config["MAIL_SERVER"] = "smtp.gmail.com"
app.config["MAIL_PORT"] = 465
app.config["MAIL_USE_SSL"] = True
app.config["MAIL_USERNAME"] = '****@gmail.com'
app.config["MAIL_PASSWORD"] = '****'

mail.init_app(app)

@app.route('/', methods=['GET', 'POST'])
def view():
  return render_template('index.html')

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

  if request.method == 'POST':
      msg = Message("Portfolio", sender='contact@example.com', recipients=['****@gmail.com'])
      msg.body = """From: %s <%s> %s %s""" % (form.name.data, form.email.data, form.message.data, "Random string")
      mail.send(msg)
      return 'Form posted.'

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


app.debug = True

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

forms.py

from wtforms import Form, TextField, TextAreaField,SubmitField,validators

class ContactForm(Form):
  name = TextField("Name", [validators.Required()])
  email = TextField("Email", [validators.Required()])
  message = TextAreaField("Message", [validators.Required()])
  submit = SubmitField("Send", [validators.Required()])

contact.html
<body>
    <h1>Contact Form:</h1>

    <form action="/contact" method="post">
          {{ form.hidden_tag }}
        <p>
          {{ form.name.label }}
          {{ form.name }}
        </p>
        <p>
          {{ form.email.label }}
          {{ form.email }}
        </p>
        <p>
          {{ form.message.label }}
          {{ form.message }}
        </p>
        <p>
          {{ form.submit }}
        </p>
      </form>
</body>

P.S。 {{from.hidden.tag}} 仅在没有括号的情况下有效

消息不是空的,表单值是。它们是空的,因为表单没有验证(你甚至没有检查它的有效性)。它无效,因为您没有将 request.form 数据传递给表单。这不会自动发生,并且 hidden_tag 不可用,因为您继承自 wtforms.Form 而不是 flask_wtf.Form

from flask_wtf import Form

class ContactForm(Form):
    ...

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

    if form.validate_on_submit():
        # send a message and return something

    return render_template('contact.html', form=form)

一定要在模板中调用 form.hidden_tag(),因为如果没有隐藏的 CSRF 字段,Flask-WTF 的表单将无法验证。