如何在尝试使用flask-mail发送电子邮件时解决builtins.ConnectionRefusedError错误

时间:2016-09-26 12:08:04

标签: python email flask flask-mail

我在python中使用Flask框架制作一个简单的WebApp。它将从我的网站(www.anshulbansal.esy.es)获取用户输入的电子邮件和名称,并将检查数据库中是否存在电子邮件(此处数据库现在被认为是字典)然后它将无法进一步工作,但如果它没有&#39 ; t存在于数据库中,它将向提交的电子邮件发送随机链接,如果用户单击该链接,则其信息将添加到我的数据库中。

它已经差不多完成但是这个错误阻碍了我。看看这段代码:

from flask import Flask, render_template, request, redirect, url_for
from flask_mail import Mail, Message
import random
import string


def random_generator(size=6, chars=string.ascii_letters + string.digits):
    return ''.join(random.choice(chars) for x in range(size))


subscribers_d = {'anshul.bansal5@yahoo.com': 'Anshul Bansal', 'anshul.bansal3@yahoo.com': 'Bansal', 'anshul.bansal@yahoo.com': 'Anshul',}

app = Flask(__name__)
mail = Mail(app)

app.config.update(
    MAIL_SERVER='smtp.gmail.com',
    MAIL_PORT=465,
    MAIL_USE_TLS = False,
    MAIL_USE_SSL=True,
    MAIL_USERNAME='anshul.bansal950@gmail.com',
    MAIL_PASSWORD="It's Secret"
)


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


@app.route('/submit', methods=['POST'])
def submit():
    if request.method == "POST":
        v_name = request.form['vname']
        v_email = request.form['vemail']
        return send_mail(v_name, v_email)
    else:
        return redirect(url_for("/"))

random_link_sent = random_generator(20)


@app.route("/")
def send_mail(v_name, v_email):
    if v_email in subscribers_d:
        return "Oh! It seems that you have already registered."
    else:
        msg = Message('Confirm Subscription', sender=['anshul.bansal950@gmail.com'], recipients=[v_email])
        msg.html = "<h3>Confirm Subscription</h3>" \
           "<p>Hi! </p>" + v_name + "<p> , Please click on below link to subscribe</p>" \
            "Link: " + ' www.anshulbansal.esy.es/' + random_link_sent
        mail.send(msg)
        return 'Check Your Inbox For Confirmation Email'


@app.route("/<random_link_sent>")
def confirm(random_link_sent):
    return "You have registered on " + random_link_sent
    subscribers_d[v_email] = v_name


if __name__ == "__main__":
    app.run(debug=True)

但是这段代码给了我一个builtins.ConnectionRefusedError错误。 但在2-3次发送电子邮件尝试成功之前没有任何错误。 我该如何解决?

Here is the screenshot of error

1 个答案:

答案 0 :(得分:2)

您应该在初始化Mail之前更新配置:

app = Flask(__name__)

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

mail = Mail(app)