Flask-Mail:空消息

时间:2015-10-27 18:37:13

标签: python flask flask-wtforms flask-mail

目前我正在尝试使用烧瓶,烧瓶邮件和烧瓶-WTF创建联系页面。正在发送消息,但我只获得“发件人:无无随机字符串”。你能告诉我,我做错了吗?

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}}仅适用于不支持

1 个答案:

答案 0 :(得分:1)

消息不为空,表单值为。它们是空的,因为表格没有验证(你甚至没有检查它的有效性)。它无效,因为您没有将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的表单将无法验证。