使用flask发送电子邮件

时间:2013-10-27 06:05:01

标签: python email flask

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

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

以下是代码:

routes.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")

1 个答案:

答案 0 :(得分:0)

这是一个示例:

<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>

根据需要进行编辑。请记住,您还必须更改烧瓶代码才能使用此代码。