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

How do I resolve builtins.ConnectionRefusedError error in attempting to send email using flask-mail

我正在 python 中使用 Flask 框架制作一个简单的 WebApp。它将从我的网站 (www.anshulbansal.esy.es) 获取用户输入的电子邮件和姓名,并将检查电子邮件是否存在于数据库中(这里的数据库目前被认为是字典)然后它将无法进一步工作,但如果它不存在存在于数据库中,它将随机发送一个 link 到提交的电子邮件,如果用户单击 link,那么它的信息将被添加到我的数据库中。

快完成了,但是这个错误挡住了我的路。查看此代码:

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

您应该在初始化 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)