gpt4 book ai didi

python - 使用 flask 发送电子邮件

转载 作者:行者123 更新时间:2023-12-03 15:48:14 26 4
gpt4 key购买 nike

我正在使用 Flask 向在联系页面中提交表单的用户发送电子邮件。

我试图自己测试它,但即使我填写了整个表格。每次我点击提交时,我都会收到一个验证错误,提示我必须填写表格。在我的日志中,它说我得到了 200,这意味着该帖子是成功的。

这是代码:

路线.py

from flask import Flask, render_template, request, flash
from forms import ContactForm
from flask.ext.mail import Message, Mail


mail = Mail()

app = Flask(__name__)

app.secret_key = 'development key'

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

mail.init_app(app)


app = Flask(__name__)
app.secret_key = 'development key'

@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="contact@gmail.com")
msg.body = """
From: %s <%s>
%s
""" % (form.name.data, form.email.data, form.message.data)
mail.send(msg)

return 'Form posted.'

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

Forms.py
from flask.ext.wtf import Form
from wtforms import Form, TextField, TextAreaField, SubmitField, validators, ValidationError

class ContactForm(Form):
name = TextField("Name", [validators.Required("Please Enter Your Name")])
email = TextField("Email",[validators.Required("Please enter your email address"), validators.email("Please enter your email address")])
subject = TextField("Subject", [validators.Required("Please enter a subject.")])
message = TextAreaField("Message", [validators.Required("Please enter a message.")])
submit = SubmitField("Send")

最佳答案

这是一个例子:

<form action="mailto:someone@example.com" method="post" enctype="text/plain">
<tr>
<td>Code name</td>
<td><input type='text' name='codename' placeholder="name your code" size=20 /></td>
</tr>
<tr>
<td>Name</td>
<td><input type='text' name='name' maxlength=20 size=20 /></td>
</tr>
<tr>
<td>Code</td><br/>
<td><textarea name='code' rows=4 cols=50></textarea></td>
</tr>
<tr>
<td></td>
<td><input type='submit' value='Submit Python Code' /></td>
</tr>
</form>

将此编辑为您需要的任何内容。请记住,您还必须更改您的 flask 代码才能使用它。

关于python - 使用 flask 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19615166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com