6

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='noreply@demo.com',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', 'noreply@demo.com')

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', 'noreply@demo.com')

Brett Cannon
  • 14,438
  • 3
  • 45
  • 40

8 Answers8

9

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
evyatar weiss
  • 140
  • 1
  • 5
  • i tried this. When i tried `print(os.environ.get("EMAIL_USER"))` It worked. But when i tried to run the server, it still gave the same error –  Feb 28 '21 at 07:46
  • Okay,it worked. Closed my cmd and again restarted it. It worked. –  Feb 28 '21 at 07:50
  • Same. I was getting the same error when I ran the script in VS Code and opened the `flask shell` session in the Powershell within VS Code. When I did it again in Powershell outside VS Code, it worked. – BallpenMan Nov 26 '21 at 12:39
1

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.

Striker
  • 15
  • 2
0

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: test@demo.com 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 (test@demo.com) eg: #$62GNMi.

  • open cmd
  • echo %EMAIL_USER%
  • It should display the mail which we gave in environment variables(test@demo.com), 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

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
0

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

Amar Kumar
  • 2,392
  • 2
  • 25
  • 33
0

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!)

  1. 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.
0

IF YOUR PROJECT IS RUNNING ON LOCALHOST

1.

  • Go to your google account/security, for the email you are using to send emails
  • Navigate to 2-Step Verification and turn it on.
  • Scroll to the bottom of the and click App passwords
  • Generate an app password that you'll use for your app to log in your google account and send an email.
  • Save your password to add it to your project...
  • On your terminal navigate to your root directory, cd.
  • Open the .bashrc file with your favourite text editor vi .bashrc
  • Add this line at the top of the file add export USER_EMAIL="your_email@gmail.com" export USER_PASSWORD="the app password you generated"
  • Save it and close the file. esc :wq
  • Go to settings.py on your project under the email configuration, replace EMAIL_HOST_USER value with: os.environ.get('USER_EMAIL') and the value of EMAIL_HOST_PASSWORD with: os.environ.get('USER_PASSWORD')
  • Navigate to your project directory and fetch the changes made in the .bashrc file with source ~/.bashrc
  • Restart your Server and this should work.

To confirm the credentials, create a simple python file check_credential.py add the following then run it import os my_email = os.environ.get('USER_EMAIL') my_password = os.environ.get('USER_PASSWORD') print(my_email, my_password)

The printed credentials should be similar to the ones in the .bashrc file and on your windows environment variables

Zebby
  • 11
  • 2
0

IF YOUR PROJECT IS HOSTED

1.

  • Go to your google account/security, for the email you are using to send emails.
  • Navigate to 2-Step Verification and turn it on.
  • Scroll to the bottom of the page and click App passwords
  • Generate an app password that you'll use for your app to log in your google account and send an email.
  • On your Hosting service e.g railway, navigate to variables.
  • Create 2 variables, USER_EMAIL with value equal to email address you are using for the project and variable USER_PASSWORD with value equal to app password generated.
  • Redeploy your app and it should work

Note: After generating the app password make sure not to use it anywhere else other than your app since it won't work and you'll have to generate a new one

Zebby
  • 11
  • 2