Skip to main content
 首页 » 编程设计

python之SMTP 服务器断开连接 : please run connect() first

2025年05月04日13bhlsheji

我正在探索 Flask 并尝试设置一个具有安全注册和登录功能的简单 Web 应用程序。我正在使用 Flask-Security 来执行此操作。不幸的是,当我导航到发送确认页面时出现错误:“smtpserverdisconnected:请先运行 connect()”。

下面是我写的相关文件。 run.py 驱动整个应用程序。

run.py(在 app 文件夹旁边)

#!venv/bin/python 
from app import app 
app.run(debug = True) 

下面的所有内容都在 app 文件夹中

__init__.py

from flask import Flask 
from flask.ext.mail import Mail 
from flask.ext.sqlalchemy import SQLAlchemy 
 
app = Flask(__name__) 
app.config.from_object('config') 
 
db = SQLAlchemy(app) 
mail = Mail(app) 
 
import models 
import views 
 
@app.before_first_request 
def create_user(): 
    db.create_all() 
    models.user_datastore.create_user(email = 'user@example.com', 
            password = 'password') 
    db.session.commit() 
 
if __name__ == '__main__': 
    app.run() 

模型.py

from app import db, app 
from flask.ext.sqlalchemy import SQLAlchemy 
from flask.ext.security import SQLAlchemyUserDatastore,\ 
        UserMixin, RoleMixin, Security 
 
roles_users = db.Table('roles_users', 
        db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), 
        db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) 
 
class Role(db.Model, RoleMixin): 
    id = db.Column(db.Integer(), primary_key = True) 
    name = db.Column(db.String(80), unique = True) 
    description = db.Column(db.String(255)) 
 
class User(db.Model, UserMixin): 
    id = db.Column(db.Integer, primary_key = True) 
    email = db.Column(db.String(255), unique = True) 
    password = db.Column(db.String(255)) 
    active = db.Column(db.Boolean()) 
    confirmed_at = db.Column(db.DateTime()) 
    roles = db.relationship('Role', secondary = roles_users, 
            backref = db.backref('users', lazy = 'dynamic')) 
 
user_datastore = SQLAlchemyUserDatastore(db, User, Role) 
security = Security(app, user_datastore) 

View .py

from app import app 
from flask import render_template 
from flask.ext.security import login_required 
 
@app.route('/') 
@login_required 
def index(): 
    return render_template('index.html') 

编辑:此外,这是我正在使用的配置文件

DEBUG      = True 
SECRET_KEY = 'secret' 
SQLALCHEMY_DATABASE_URI = 'sqlite://' 
 
SECURITY_PASSWORD_HASH = 'sha512_crypt' 
SECURITY_PASSWORD_SALT = 'salt' 
SECURITY_CONFIRMABLE = True 
SECURITY_REGISTERABLE = True 
SECURITY_RECOVERABLE = True 
SECURITY_TRACKABLE = True 
SECURITY_CHANGEABLE = True 
 
MAIL_SERVER = 'smtp.zoho.com' 
MAIL_PORT = 465 
MAIL_USE_TLS = False 
MAIL_USE_SSL = True 
MAIL_DEBUG = True 
MAIL_USERNAME = 'myaddress@mydomain' 
MAIL_PASSWORD = 'password' 

请您参考如下方法:

好的,所以我想出了问题所在。默认情况下,flask-security 被设置为以“localhost”发送邮件。我的邮件提供商是 Zoho,但我只是将它们用作我运行的域的邮件服务器。我的邮件设置是这样的,我只能从某些地址发送邮件。因为“localhost”不是这些 flask-security 之一,所以无法连接到 Zoho 的服务器。

所以解决方案是在我的配置文件中添加一行

SECURITY_EMAIL_SENDER = 'valid_email@my_domain.com' 

希望这会为其他人节省一些时间来弄清楚为什么 flask-security 的电子邮件不起作用。