目前我正在尝试使用flask、flask-mail 和flask-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>
PS {{from.hidden.tag}} 仅在没有括号的情况下有效