5

here the main flask-mail code which I used for sending mail for reset password in case user forgot but when I run and code it saw me smtplib.SMTPServerDisconnected: Connection unexpectedly closed

here below is init.py file code

import os
from flask_mail import Mail
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager

app = Flask(__name__)

app.config['SECRET_KEY'] = '7f09c01a4f942b0812be4cb86e065f77'
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///site.db'

db=SQLAlchemy(app)
bcrypt=Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view='login'
login_manager.login_message_category='info'

app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = 'sender@gmail.com'
app.config['MAIL_PASSWORD'] = 'password'

mail = Mail(app)

from index import routes

and routes.py file

import os
import binascii
from PIL import Image
from flask import render_template,url_for, flash, redirect, request, abort
from index import app,db,bcrypt,mail
from index.forms import (RegistrationForm,LoginForm,UpdateAccountForm,PostForm,
                        RequestResetForm,ResetPasswordForm)
from index.models import User, Post
from flask_login import login_user, current_user, logout_user, login_required
from flask_mail import Message

token = user.get_reset_token()
    msg = Message('Password Reset Request',
                  sender="*****@gmail.com",
                  recipients=[user.email])
    msg.body = '''To reset your password, visit the following link:{}
If you did not make this request then simply ignore this email and no changes will be made.
'''.format((url_for('reset_token', token=token, _external=True)))
    
    mail.send(msg)

here is get_reset_token methode :

from datetime import datetime
from index import db, login_manager,app
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from flask_login import UserMixin

def get_reset_token(self, expires_sec=1800):
        s = Serializer(app.config['SECRET_KEY'], expires_sec)
        return s.dumps({'user_id': self.id}).decode('utf-8')

I also saw below code on StackOverflow but that also didn't work

app.config['MAIL_USE_SSL'] = True
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'sender@gmail.com'
app.config['MAIL_PASSWORD'] = 'password'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
Ketan Suthar
  • 365
  • 4
  • 13
  • seems ok to me. Have you tried using 'smtp.gmail.com' instead. Failing that if you use two-factor-authentication then this won't work unless you setup an app password from within your administration panel control in gmail. And obviously your username and password have to then be entered correctly but I think you'll already get that! – Attack68 Oct 20 '18 at 06:21

0 Answers0