Flask-WTF表单,在用户提交表单时不发送电子邮件

时间:2016-07-22 09:18:26

标签: python flask flask-wtforms

我决定遵循本教程(https://www.boxcontrol.net/adding-contact-form-to-your-site-using-flask-and-python3.html),但创建了一种不同类型的表单,用户输入其个人信息,并将提交的表单通过电子邮件发送到我的G-mail帐户。但是在提交表格后我没有收到任何电子邮件或错误。

我做的第一件事就是创建ContactForm类。

from flask_wtf import Form
from wtforms import TextField, TextAreaField, SubmitField
from wtforms.validators import InputRequired

class ContactForm(Form):
  name = TextField("Fullname", validators=[InputRequired('Please enter your name.')])
  email = TextField("Email",  validators=[InputRequired("Please enter your email address.")])
  NoChildren = TextField("Number of children dependants (if applicable):",  validators=[InputRequired("Please enter a subject.")])
  NoAdults = TextField("Number of adult dependants (if applicable):",  validators=[InputRequired("Please enter a subject.")])
  travel = TextField("Will you be travelling alone?",  validators=[InputRequired("Please enter a subject.")])
  marriage = TextField("What is your marital status?",  validators=[InputRequired("Please enter a subject.")])
  nation = TextField("Current nationality(ies):",  validators=[InputRequired("Please enter a subject.")])
  dob = TextField("Date of birth:",  validators=[InputRequired("Please enter a subject.")])
  phone = TextField("Phone number:",  validators=[InputRequired("Please enter a subject.")])
  nonukaddress = TextField("Your current non-UK address:",  validators=[InputRequired("Please enter a subject.")])
  ukaddress = TextField("UK address:",  validators=[InputRequired("Please enter a subject.")])
  history = TextField("Do you have any criminal history?",  validators=[InputRequired("Please enter a subject.")])
  hadvisa = TextField("Have you ever had any other visas?",  validators=[InputRequired("Please enter a subject.")])
  refusevisa = TextField("Have you been refused a visa before?",  validators=[InputRequired("Please enter a subject.")])
  medical = TextField("Did you receive any medical treatment in the UK?",  validators=[InputRequired("Please enter a subject.")])
  letter = TextField("Do you have a letter from a UK regulated financial institution confirming that original evidence of funds has been supplied?",  validators=[InputRequired("Please enter a subject.")])
  sole = TextField("Are you the sole owner of the money?",  validators=[InputRequired("Please enter a subject.")])
  additional = TextAreaField("Additional information/questions/requests:",  validators=[InputRequired("Please enter a message.")])
  submit = SubmitField("Send")

然后我为表单创建了HTML模板。

{% block content %}
  <h2>Contact</h2>

  {% if success %}
    <p>Thank you for your message. We'll get back to you shortly.</p>

  {% else %}  
    {% for message in form.name.errors %}
      <div class="flash">{{ message }}</div>
    {% endfor %}

    {% for message in form.email.errors %}
      <div class="flash">{{ message }}</div>
    {% endfor %}

    <form action="{{ url_for('contact') }}" method=post>
      {{ form.hidden_tag() }}

      {{ form.name.label }}
      {{ form.name }}

      {{ form.email.label }}
      {{ form.email }}

      {{ form.NoChildren.label }}
      {{ form.NoChildren }}

      {{ form.travel.label }}
      {{ form.travel }}

      {{ form.marriage.label }}
      {{ form.marriage }}

      {{ form.nation.label }}
      {{ form.nation }}

      {{ form.dob.label }}
      {{ form.dob }}

      {{ form.phone.label }}
      {{ form.phone }}

      {{ form.nonukaddress.label }}
      {{ form.nonukaddress }}

      {{ form.ukaddress.label }}
      {{ form.ukaddress }}

      {{ form.history.label }}
      {{ form.history }}

      {{ form.hadvisa.label }}
      {{ form.hadvisa }}

      {{ form.refusevisa.label }}
      {{ form.refusevisa }}

      {{ form.parents.label }}
      {{ form.parents }}

      {{ form.medical.label }}
      {{ form.medical }}

      {{ form.letter.label }}
      {{ form.letter }}

      {{ form.sole.label }}
      {{ form.sole }}

      {{ form.ukbank.label }}
      {{ form.ukbank }}

      {{ form.additional.label }}
      {{ form.additional }}

      {{ form.submit }}
    </form> 
  {% endif %}
{% endblock %} 

我的主烧瓶文件看起来像这样。

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

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"] = 'your_email@example.com'
app.config["MAIL_PASSWORD"] = '*******'

mail.init_app(app)

@app.route('/')
def index():
  return render_template('index.html')


@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@example.com', recipients=['your_email@example.com'])
      msg.body = """
      From:%s <%s>,
            %s
            """ % (form.name.data, form.email.data, form.message.data,form.NoChildren.data,form.travel.data,form.marriage.data, form.nation.data, form.dob.data, form.phone.data, form.nonukaddress.data, form.ukaddress.data, form.history.data, form.hadvisa.data, form.refusevisa.data, form.parents.data, form.medical.data,  form.letter.data, form.sole.data, form.ukbank.data, form.additional.data)
      mail.send(msg)

      return render_template('contact.html', success=True)

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

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

2 个答案:

答案 0 :(得分:0)

在你有很多活动部件的时刻打破问题。如果您没有收到错误,我最初的想法是您的电子邮件会被发送到垃圾邮件/垃圾邮件。

如果您创建一个只发送静态电子邮件的新视图,它是否有效?

@app.route('/testemail')
def send_test_email():
    msg = Message('Title',sender='you@yours.com', recipients=['you@yours.com'])
    msg.body('Hello...')
    mail.send(msg)

如果没有 - 那么您知道问题与您的代码的电子邮件方面有关,那么您可以开始查看MAIL_DEBUG中可用的Flask-Mail选项,检查垃圾邮件文件夹等。

通常,您可能会发现使用像您这样处理电子邮件传递的服务更容易,更可靠,而不是自己发送SMTP请求,使用他们的Python库向他们发送您的电子邮件数据,然后他们会处理其余的事情。我个人使用Sendgrid,但有无数的公司提供类似的服务。

答案 1 :(得分:0)

如果您没有收到任何错误且未发送任何电子邮件,请设置MAIL_DEBUG=True。 Flask-Mail使用可以set调试级别的smtplib模块。在初始化邮件之前,请尝试更新config

app = Flask(__name__)

app.config.update(dict(
    DEBUG = True,
    MAIL_SERVER = 'smtp.gmail.com',
    MAIL_PORT = 587,
    MAIL_USE_TLS = True,
    MAIL_USE_SSL = False,
    MAIL_USERNAME = 'my_username@gmail.com',
    MAIL_PASSWORD = 'my_password',
))

mail = Mail(app)

请参阅this