4
votes

init.py

from flask_wtf import FlaskForm 
from wtforms import StringField,SubmitField,PasswordField
from wtforms.validators import DataRequired,Length,Email
from flask import Flask
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail
import os






app = Flask(__name__)
app.config['SECRET_KEY'] = 'r3t058rf3409tyh2g-rwigGWRIGh[g'
app.config['MAIL_SERVER']='smtp.googlemail.com'
app.config['MAIL_PORT']=587
app.config['MAIL_USE_TLS']=True
app.config['MAIL_USERNAME']=os.environ.get('EMAIL_USER')
app.config['MAIL_PASSWORD']=os.environ.get('EMAIL_PASS')
mail=Mail(app)


db = SQLAlchemy(app)

logMg=LoginManager(app)
logMg.login_view='login'
logMg.login_message_category='info'

bcrypt=Bcrypt()

from portfolio import routes   

Routes.py

def send_reset_email(user):
token=user.get_reset_token()
msg=Message('Password Reset Request',sender='[email protected]',recipients=[user.email])
msg.body=''' To reset your password visit the following link:
{ url_for('reset_token',token=token,_external=True) }
If you did not Make request please contact our Team
'''
mail.send(msg)

@app.route("/reset_password",methods=['GET','POST'])
def reset_request():
    if current_user.is_authenticated:
       return redirect(url_for('admin')) 
    form=RequestResetForm()
    if form.validate_on_submit():
        user=User.query.filter_by(email=form.email.data).first()
        send_reset_email(user)
        flash('Reset Email Link Sent')
        return redirect(url_for('login'))
    return render_template("reset_request.html",form=form,legend='Edit Post')

@app.route("/reset_password/<token>",methods=['GET','POST'])
def reset_token():
    if current_user.is_authenticated:
       return redirect(url_for('admin'))
    user=User.verify_reset_token(token)
    if user is None:
        flash('Invalid or Expired Token','warning')
        return redirect(url_for(reset_request))
    form=ResetPasswordForm()
    if form.validate_on_submit():
        hashed_password=bcrypt.generate_password_hash(form.password.data).decode('utf-8')
        user.password=hashed_password
        db.session.commit()
        flash('Password Changed!','success')
        return redirect(url_for('Login'))
    return render_template('reset_token',form=form,legend='Reset Password Form')

Keep getting this error to authenticate sender I have tried changing to my email and enabling IMAP setting but did not work

Returns

smtplib.SMTPSenderRefused smtplib.SMTPSenderRefused: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError t20sm2139075wmi.2 - gsmtp', '[email protected]')

Traceback (most recent call last) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\flask\app.py", line 2464, in call return self.wsgi_app(environ, start_response)

File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\flask\app.py", line 2450, in wsgi_app response = self.handle_exception(e)

File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\flask\app.py", line 1867, in handle_exception reraise(exc_type, exc_value, tb)

File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\flask_compat.py", line 39, in reraise raise value

File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\flask\app.py", line 2447, in wsgi_app response = self.full_dispatch_request()

File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request rv = self.handle_user_exception(e)

File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\flask\app.py", line 1821, in handle_user_exception reraise(exc_type, exc_value, tb)

File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\flask_compat.py", line 39, in reraise raise value

File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request rv = self.dispatch_request()

File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\flask\app.py", line 1936, in dispatch_request return self.view_functionsrule.endpoint

File "C:\Dev\Visual Studio 2019\Projects\portfolio\portfolio\routes.py", line 177, in reset_request send_reset_email(user)

File "C:\Dev\Visual Studio 2019\Projects\portfolio\portfolio\routes.py", line 168, in send_reset_email mail.send(msg)

File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\flask_mail.py", line 492, in send message.send(connection)

File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\flask_mail.py", line 427, in send connection.send(self)

File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\flask_mail.py", line 192, in send message.rcpt_options)

File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\smtplib.py", line 867, in sendmail raise SMTPSenderRefused(code, resp, from_addr)

smtplib.SMTPSenderRefused: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError t20sm2139075wmi.2 - gsmtp', '[email protected]')

6

6 Answers

7
votes

Prerequisite

  1. you need a valid gmail account which means you need to know Email address and Password
  2. you have to add those email address and password to Windows System Variable. (EMAIL_USER and EMAIL_PASSWORD)
  3. you need to turn on ' Less secure app access' in your Gmail Account Security. you can google it.

Once all above prerequisite has been done, try to check that you can get those variable from command line first.

  1. go to command prompt, type Echo %EMAIL_USER% and the expect return output is your email. if the %EMAIL_USER% also return then you configure step 2 above incorrectly.

  2. Do not execute Python file from VS Code. This issue similar to Pycharm user as well. I think the VS Code may not be able to access OS environment somehow (possibly I do not sure how to configure that.) The alternative solution is activate your Virtual Environment via Command Line and then run Python via Command Line -- Open command prompt and go to your Python Program folder. CD Scripts and execute 'activate'

2.1 test whether your Python can get OS environment by execute Python and import os and then

print (os.environ.get("EMAIL_USER")) 

The expect output is your email address.

2.2 Once it done, you go back to your main program folder and execute Python run.py

  1. Try to reset password. Email should be sent. I got the email now.

Seccond thing that you can try: instead of using TLS,

app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
1
votes

I got same error and it solved when I ran flask script from new terminal. Make sure to restart your terminal and IDE when you make changes to environment variables.

0
votes

Prerequisite

Check in Control Panel\System and Security\System->Advance Settings->Environment Variables. Click on New --> Variable name -- whatever the variable you gave in your init.py file(EMAIL_USER), variable value --- The email which you want to give eg: [email protected] Similarly for password: Variable name -- whatever the variable you gave in your init.py file(EMAIL_PASS), variable value --- The password linked to that mail ([email protected]) eg: #$62GNMi.

  • open cmd
  • echo %EMAIL_USER%
  • It should display the mail which we gave in environment variables([email protected]), if not close all the opened cmd prompts and open freshly and try.
  • Similarly for the echo %EMAIL_PASS%.

Note:

  • If you are using any IDE like sublime text, pycharm,.... make sure you close the virtual environment and restart the virtual environment if you are in windows got to your project path and use (env_name\Scripts\activate.bat) and restart your application.

  • Also enable Less secure app access in your gmail account https://www.google.com/settings/security/lesssecureapps

0
votes

You do it by CoreySchafer's Flask lessons, me too. So, i found desicion.

If you have Ubuntu or manjaro, you need to write your Environment Variables not to .bash_profile file, but to .bashrc and then you need to reload .bashrc file by typing . ~/.bashrc or source ~/.bashrc

If doesnt work, reboot your system. It worked for me.

0
votes

In my case the problem was with "VS Code Python terminal."

In addition to the accepted answer:

Try Switching from "Python terminal" to "CMD terminal" worked for me on VS Code!

Click on + button on VS code terminal and select CMD terminal and run your program. enter image description here

0
votes

1. Turning on 'less secure apps' settings as mail domain Administrator

1.Open your Google Admin console (admin.google.com). 2.Click Security > Basic settings. 3.Under Less secure apps, select Go to settings for less secure apps. In the subwindow, select the Enforce access to less secure apps for all users radio button. (You can also use the Allow users to manage their access to less secure apps, but don't forget to turn on the less secure apps option in users' settings then!) 5.Click the Save button.

2. Turning on 'less secure apps' settings as mailbox user

1.Go to your (Google Account). 2.On the left navigation panel, click Security. 3.On the bottom of the page, in the Less secure app access panel, click Turn on access. If you don't see this setting, your administrator might have turned off less secure app account access (check the instruction above). 4.Click the Save button.