使用Flask-Mail发送电子邮件 - socket.gaierror

时间:2014-01-08 05:22:22

标签: python-2.7 flask flask-wtforms flask-mail

我正在使用Flask和Flask-Mail构建一个简单的联系页面。我按照本教程构建了应用程序 - Add a contact page - 现在当我尝试发送消息时,我收到了错误gaierror: [Errno -2] Name or service not known。我一直在谷歌搜索错误一段时间,并没有在线找到任何类似的例子。我甚至无法弄清楚它找不到的名称或服务。

回溯页面将让我展开一行并执行一些Python代码。它提供了一个dump()函数,它将向我显示所有变量,并且可以在对象上调用它们以查看它们的信息(如果这有用)。

routes.py:

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.google.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = 'email'
app.config['MAIL_PASSWORD'] = 'email'

mail.init_app(app)
@app.route('/contact', methods=['GET', 'POST'])
def contact():
    form = ContactForm()

    if request.method == 'POST':
        if not form.validate():

形式:

from flask.ext.wtf import Form, validators
from wtforms.fields import TextField, TextAreaField, SubmitField
import wtforms


class ContactForm(Form):
    name = TextField("Name", [wtforms.validators.Required('Please enter your name')])
    email = TextField("Email", [wtforms.validators.Required('Please enter your email'), wtforms.validators.Email()])
    subject = TextField("Subject", [wtforms.validators.Required('Please enter a subject')])
    message = TextAreaField("Message", [wtforms.validators.Required('Please enter a message')])
    submit = SubmitField("Send")
            flash('All fields are required.')
            return render_template('contact.html', form=form)
        else:
            msg = Message(form.subject.data, sender='imauld@gmail.com', recipients=['imauld@gmail.com'])
            msg.body = """From: %s <%s> %s""" % (form.name.data, form.email.data, form.message.data)
            mail.send(msg)
            return render_template('contact.html', success=True)
    elif request.method == 'GET':
        return render_template('contact.html', form=form)

追溯:

File "/home/ian/PycharmProjects/flaskapp/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__

return self.wsgi_app(environ, start_response)

File "/home/ian/PycharmProjects/flaskapp/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app

response = self.make_response(self.handle_exception(e))

File "/home/ian/PycharmProjects/flaskapp/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception

reraise(exc_type, exc_value, tb)

File "/home/ian/PycharmProjects/flaskapp/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app

response = self.full_dispatch_request()

File "/home/ian/PycharmProjects/flaskapp/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request

rv = self.handle_user_exception(e)

File "/home/ian/PycharmProjects/flaskapp/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception

reraise(exc_type, exc_value, tb)

File "/home/ian/PycharmProjects/flaskapp/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request

rv = self.dispatch_request()

File "/home/ian/PycharmProjects/flaskapp/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request

return self.view_functions[rule.endpoint](**req.view_args)

File "/home/ian/PycharmProjects/flaskapp/app/routes.py", line 39, in contact

mail.send(msg)

File "/home/ian/PycharmProjects/flaskapp/lib/python2.7/site-packages/flask_mail.py", line 415, in send

with self.connect() as connection:

File "/home/ian/PycharmProjects/flaskapp/lib/python2.7/site-packages/flask_mail.py", line 123, in __enter__

self.host = self.configure_host()

File "/home/ian/PycharmProjects/flaskapp/lib/python2.7/site-packages/flask_mail.py", line 135, in configure_host

host = smtplib.SMTP_SSL(self.mail.server, self.mail.port)

File "/usr/lib/python2.7/smtplib.py", line 776, in __init__

SMTP.__init__(self, host, port, local_hostname, timeout)

File "/usr/lib/python2.7/smtplib.py", line 249, in __init__

(code, msg) = self.connect(host, port)

File "/usr/lib/python2.7/smtplib.py", line 309, in connect

self.sock = self._get_socket(host, port, self.timeout)

File "/usr/lib/python2.7/smtplib.py", line 781, in _get_socket

new_socket = socket.create_connection((host, port), timeout)

File "/usr/lib/python2.7/socket.py", line 553, in create_connection

for res in getaddrinfo(host, port, 0, SOCK_STREAM):

gaierror: [Errno -2] Name or service not known

2 个答案:

答案 0 :(得分:1)

我在这里的第一次尝试,但只是挑选我能看到的东西。我假设你已经从每个文件复制了整个代码。如果我错了,请纠正我。

确保routes.py从flask中导入必要的类(“request”对于提交表单是必不可少的,因为它确定请求方法是GET还是POST:

from flask import Flask, render_template, request, flash

你的Forms.py ...注意:你实际上并不需要导入整个wtforms模块......

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

在routes.py代码中,如果“not”语句有一个不必要的布尔运算符:

if request.method == 'POST':
    if not form.validate():

它应该包含一个比较运算符和布尔值,因为它在Lalith's Post中:

if form.validate() == False:
    flash("All fields...

您的forms.py不应包含以下任何内容:

flash('All fields are required.')
        return render_template('contact.html', form=form)
    else:
        msg = Message(form.subject.data, sender='imauld@gmail.com', recipients=['imauld@gmail.com'])
        msg.body = """From: %s <%s> %s""" % (form.name.data, form.email.data, form.message.data)
        mail.send(msg)
        return render_template('contact.html', success=True)
elif request.method == 'GET':
    return render_template('contact.html', form=form)

它应该都包含在routes.py中的contact函数中,如下所示:

def contact():
form = ContactForm()

if request.method == 'POST':
    if not form.validate():
        flash('All fields are required.')
        return render_template('contact.html', form=form)
    else:
        msg = Message(form.subject.data, sender='imauld@gmail.com', recipients=['imauld@gmail.com'])
        msg.body = """From: %s <%s> %s""" % (form.name.data, form.email.data, form.message.data)
        mail.send(msg)
        return render_template('contact.html', success=True)
elif request.method == 'GET':
    return render_template('contact.html', form=form)

最后我知道这看起来很明显,但请确保在这里用您的真实电子邮件和密码替换“email”:

app.config['MAIL_USERNAME'] = 'email' 
app.config['MAIL_PASSWORD'] = 'email'
祝你好运。希望这会有所帮助。

答案 1 :(得分:0)

行。我知道这个问题已经有4年了,但这是我的解决方案。 有一个BUG。 您只需要在app.config.from_object之后将配置参数添加到烧瓶应用程序。

from config import config
app.config.from_object(config[config_name])
config[config_name].init_app(app)
app.config.update( DEBUG=True, MAIL_SERVER='smtp.gmail.com',
                   MAIL_PORT=587, MAIL_USE_SSL=False, MAIL_USE_TLS=True, MAIL_USERNAME = 'your@gmail.com')

在config.py中我有这两个参数:

MAIL_PASSWORD = 'password'
MAIL_DEFAULT_SENDER = 'your@gmail.com'
# IMPORTANT - the rest of the mail parameters are set inside the __init__.py because they don't work here -> BUG

如果有人有时间找出哪些参数不适用于app.config.from_object(..),他可以添加其他答案。

并且不要忘记将Google安全设备切换为接受安全性较低的应用。否则它将无法工作。 问候