简体   繁体   中英

flask-mail : ConnectionRefusedError when trying to send an email from flask server

I am doing a web application where the only users are adminstrators who may received mail from server once a week. Currently, I'm just trying to send mail from click command to test the module but I always get a 'ConnectionRefusedError [WinError 10061]...

I looked at different posts where the problem was barely the same but none of them resolved mine.

Here's my flask configuration

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail ,Message
from flask_login import LoginManager
from apscheduler.schedulers.background import BackgroundScheduler
import os.path

def mkpath(p):
    return os.path.normpath(
        os.path.join(
            os.path.dirname(__file__),
            p
        )
    )

app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = "847b5600-f639-4d07-803e-de716f4e89b7"
app.config['SQLALCHEMY_DATABASE_URI'] = (
    'sqlite:///'+mkpath('./app.db')
)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

UPLOAD_FOLDER_CSV = "static/tmp/"
ALLOWED_EXTENSION = set(['csv', 'xls'])
UPLOAD_FOLDER_FLUX = "static/flux/"

MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT = 465
MAIL_USE_TLS = False
MAIL_USE_SSL = True
MAIL_USERNAME = 'mymail@gmail.com'
MAIL_PASSWORD = 'mygmailpassword'

db = SQLAlchemy(app)
login_manager = LoginManager(app)
scheduler = BackgroundScheduler()
mail = Mail(app)

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

and here's the command I am calling to test it :

def sendmail():
    msg = Message(
                  recipients=["anothermail@gmail.com"])

    msg.body = "testing"
    mail.connect()
    mail.send(msg)

Thanks :)

You should update configuration before you initialize Mail:

app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'mymail@gmail.com'
app.config['MAIL_PASSWORD'] = 'mygmailpassword'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True

mail = Mail(app)

Then, you should allow access from less secure apps via this link .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM