Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SMTPSenderRefused: (530, '5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/m ail/answer/14257 h66sm6105022pfe.6 - gsmtp', u'Flasky Admin #167

Closed
spaceled opened this issue Jul 5, 2016 · 56 comments
Labels

Comments

@spaceled
Copy link

spaceled commented Jul 5, 2016

When I try to Register a User it shows

send: 'ehlo [10.0.2.15]\r\n'
reply: '250-smtp.gmail.com at your service, [58.97.200.89]\r\n'
reply: '250-SIZE 35882577\r\n'
reply: '250-8BITMIME\r\n'
reply: '250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH\r\n'
reply: '250-ENHANCEDSTATUSCODES\r\n'
reply: '250-PIPELINING\r\n'
reply: '250 SMTPUTF8\r\n'
reply: retcode (250); Msg: smtp.gmail.com at your service, [58.97.200.89]
SIZE 35882577
8BITMIME
AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
ENHANCEDSTATUSCODES
PIPELINING
SMTPUTF8
send: u'mail FROM:reezaul.karim@gmail.com size=1802\r\n'
reply: '530-5.5.1 Authentication Required. Learn more at\r\n'
reply: '530 5.5.1 https://support.google.com/mail/answer/14257 h66sm6105022pfe.6 - gsmtp\r\n'
reply: retcode (530); Msg: 5.5.1 Authentication Required. Learn more at
5.5.1 https://support.google.com/mail/answer/14257 h66sm6105022pfe.6 - gsmtp
send: 'rset\r\n'
reply: '250 2.1.5 Flushed h66sm6105022pfe.6 - gsmtp\r\n'
reply: retcode (250); Msg: 2.1.5 Flushed h66sm6105022pfe.6 - gsmtp
send: 'quit\r\n'
reply: '221 2.0.0 closing connection h66sm6105022pfe.6 - gsmtp\r\n'
reply: retcode (221); Msg: 2.0.0 closing connection h66sm6105022pfe.6 - gsmtp
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(_self.__args, *_self.__kwargs)
File "/vagrant/project/app/email.py", line 8, in send_async_email
mail.send(msg)
File "/usr/local/lib/python2.7/dist-packages/flask_mail.py", line 492, in send
message.send(connection)
File "/usr/local/lib/python2.7/dist-packages/flask_mail.py", line 427, in send
connection.send(self)
File "/usr/local/lib/python2.7/dist-packages/flask_mail.py", line 192, in send
message.rcpt_options)
File "/usr/lib/python2.7/smtplib.py", line 731, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
SMTPSenderRefused: (530, '5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/m
ail/answer/14257 h66sm6105022pfe.6 - gsmtp', u'Flasky Admin reezaul.karim@gmail.com')

@miguelgrinberg
Copy link
Owner

Well, the error seems pretty clear to me:

SMTPSenderRefused: (530, '5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/mail/answer/14257 by5sm3497195pad.36 - gsmtp', u'Flasky Admin spaceled@gmail.com')

Are you providing credentials to your email server? If you are, are they correct?

@spaceled
Copy link
Author

spaceled commented Jul 5, 2016

Here is my Configuration

class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SSL_DISABLE = False
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLCLCHEMY_RECORD_QUERIES = True
MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT = 465
MAIL_USE_TLS = False
MAIL_USE_SSL = True
MAIL_USERNAME = os.environ.get('user@gmail.com')
MAIL_PASSWORD = os.environ.get('password')
FLASKY_MAIL_SUBJECT_PREFIX = '[Flasky]'
FLASKY_MAIL_SENDER = 'Flasky Admin user@gmail.com'
FLASKY_ADMIN = os.environ.get('FLASKY_ADMIN')

Here I edited email and password in original.

@miguelgrinberg
Copy link
Owner

You need to set the username and password in environment variables. Read about os.environ in the Python documentation if you are not familiar with that.

@spaceled
Copy link
Author

spaceled commented Jul 6, 2016

it worked!

Thanks a lot

I changed it like..

class Config:
    SECRET_KEY =              os.environ.get('SECRET_KEY',        'SECRET_KEY')
    SSL_DISABLE = False
    SQLALCHEMY_COMMIT_ON_TEARDOWN = True
    SQLCLCHEMY_RECORD_QUERIES = True
    CSRF_ENABLED = True
    MAIL_SERVER =               os.environ.get('MAIL_SERVER',          'smtp.gmail.com')
    MAIL_USERNAME =         os.environ.get('MAIL_USERNAME',     'user@gmail.com')
    MAIL_PASSWORD =         os.environ.get('MAIL_PASSWORD',     'password')
    MAIL_SENDER =              os.environ.get('MAIL_SENDER', 'Project Admin<user@gmail.com>')
    PROJECT_ADMIN =         os.environ.get('PROJECT_ADMIN',     'PROJECT_ADMIN')
    MAIL_PORT =              int(os.environ.get('MAIL_PORT',         '465'))
    MAIL_USE_TLS =        int(os.environ.get('MAIL_USE_TLS',  False))
    MAIL_USE_SSL =        int(os.environ.get('MAIL_USE_SSL',  True))
    MAIL_SUBJECT_PREFIX = '[PROJECT]'

@spaceled spaceled closed this as completed Jul 6, 2016
@spaceled
Copy link
Author

Sir,
How can I set User permission? Please, help me if you have avail time for me.

Thanks

@miguelgrinberg
Copy link
Owner

Permissions are not assigned directly to users. Users are assigned a "role", and the role contains the list of things that are allowed (the "permissions"). If you want to assign a role to a user, just assign it to it and save it:

my_user.role = my_role
db.session.add(my_user)
db.session.commit()

@spaceled
Copy link
Author

Sir,
I tried to create blog posts from Books(p 132).But unfortunately Posts form does not appear. I tried followed book strictly but no progress. Post form does not appear. Please, find the attached image.
post-form

@spaceled spaceled reopened this Jul 30, 2016
@miguelgrinberg
Copy link
Owner

miguelgrinberg commented Jul 30, 2016

As I explained above, the user needs to be the correct role assigned so that it is allowed to post. Without that role assignment the application will not display the post form. What role is assigned to user s.paceled?

@spaceled
Copy link
Author

Sir,
This is my original models.py Pastebin.com file. I can not assign a role in my code. I want to assign Administrator for my role. How can I do this? Would you please make a time for me to review my code?

Thanks

@miguelgrinberg
Copy link
Owner

What do you mean when you say you cannot assign a role? I showed you above how to assign a role. Can you show me how you did it?

@spaceled
Copy link
Author

Sir,
here it is
capture

@spaceled
Copy link
Author

'spaceled' is my user

@miguelgrinberg
Copy link
Owner

Why are you inserting your code in the insert_roles() method? You need to run this outside of that, for example in a Python console.

@spaceled
Copy link
Author

When I run this command "python manage.py shell" it runs not prompt to shell

capture3

I am using Vagrant, Git on my Windows PC. I could not create virtualenv on Win. I tried hard but I failed to make a virtualenv on Windows Machine.

@miguelgrinberg
Copy link
Owner

You need to compare the manage.py file that you are using against the one in this repository. I'm sure you have something wrong there.

@spaceled
Copy link
Author

Sir,
"this repository" means Your original code in this repository?

@miguelgrinberg
Copy link
Owner

Yes.

@spaceled
Copy link
Author

I tried to assign User Permission to my User (spaceled). But unfortunately I think I am missing some important things.

capture5

@miguelgrinberg
Copy link
Owner

Yes. I think you need to learn about classes and objects, you are missing some very important concepts in the Python language.

You are trying to set the role on a string, not on a user object.

@spaceled
Copy link
Author

Thanks Sir
I am trying to get it in.

@HarshitBagla
Copy link

HarshitBagla commented Oct 5, 2017

Sir, I am facing an authentication problem with my flask app. The config code is written below

app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = os.environ.get('username')
app.config['MAIL_PASSWORD'] = os.environ.get('password')`

Further, I am calling the data from MySQL to compare it with today's date. The code is written below. I have commented the for loop as of now just debug the config error.

@app.route('/mailing', methods=['GET', 'POST'])
@is_logged_in
def mailing():
	#Create cursor
	cur = mysql.connection.cursor()

	#Get Tasks
	result = cur.execute("SELECT * FROM grades WHERE remind_date=%s", [now.strftime('%Y-%m-%d')])

	grades = cur.fetchone()

	# if str(grades['remind_date']) == now.strftime('%Y-%m-%d'):
	msg = Message('Good Morning', sender='jpisvideotest@gmail.com', recipients=['hbagla@jpischool.com'])
	mail.send(msg)
	
	# Close connection
	cur.close()
	return redirect(url_for('dashboard'))

@HarshitBagla
Copy link

I have also allowed my Gmail account to support access of less secure apps

@miguelgrinberg
Copy link
Owner

@HarshitBagla What's the error? The only thing I can see is that you are not setting the body of the email.

@mirbahar
Copy link

hello @miguelgrinberg i am facing email verification problem of laravel .
error:
Swift_TransportException (530)
Expected response code 250 but got code "530", with message "530-5.5.1 Authentication Required. Learn more at 530 5.5.1 https://support.google.com/mail/?p=WantAuthError p87sm32282625pfi.95 - gsmtp "
.envfile:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=test@gmail.com.com
MAIL_PASSWORD=6457234
MAIL_ENCRYPTION=tls

@miguelgrinberg
Copy link
Owner

Laravel? Are you sure you are asking in the right place? In any case, the error message sends you to a link where you can find what the problem is (it's a security feature from Gmail that you'll need to turn off).

@mirbahar
Copy link

mirbahar commented Dec 24, 2017 via email

@nicotuban
Copy link

hi sir I am facing this problem on my flask app . i want to reset the password of the user by sending a notification to gmail
smtplib.SMTPSenderRefused

smtplib.SMTPSenderRefused: (530, b'5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/mail/?p=WantAuthError o72-v6sm16878534pfk.76 - gsmtp', 'onicsbantu@gmail.com')
here's my code:

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

app = Flask(name)
app.config['SECRET_KEY'] = '30da1dc4194e2a1a79eb967d54d3944f'
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.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = os.environ.get('EMAIL_USER')
app.config['MAIL_PASSWORD'] = os.environ.get('EMAIL_PASS')
mail = Mail(app)

from flaskblog import routes

@miguelgrinberg
Copy link
Owner

Google mail requires authentication, it seems you are not passing username and password, or they are incorrect.

@JayRizzo
Copy link

JayRizzo commented Aug 14, 2018 via email

@gyandjango
Copy link

hello, @miguelgrinberg I am facing email verification problem of sending mail.
error:
SMTPSenderRefused at /info/
(530, b'5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/mail/?p=WantAuthError f67-v6sm16238307pfe.75 - gsmtp', 'gyanjha.20@gmail.com')

EMAIL_HOST='smtp.gmail.com'
EMAIL_PORT=587
MAIL_DRIVER='smtp'
EMAIL_HOST_USER='gyanjha.20@gmail.com'
#EMAIL_HOST_PASSWORD='gyan1212'
EMAIL_USE_TLS=True
EMAIL_USE_SSL=False

plz solve this problem

@miguelgrinberg
Copy link
Owner

@gyandjango You have to provide a valid password for the account, google requires authentication to send email.

@gyandjango
Copy link

Sir put valid gmail password but not send msg in gmail

@miguelgrinberg
Copy link
Owner

I can't really help you. The error message from gmail indicates you are not providing valid credentials. Review the URL they include in the error for more information.

@gyandjango
Copy link

gyandjango commented Sep 14, 2018 via email

@gyangee20
Copy link

Sir plz tail me to provide valid credentials
and send me setting

@mickey911112
Copy link

Hello,miguelgrinberg .
Nice to meet you. I am facing same issue my project.
Could you kindly help me? Here is my issue.

Request Method: POST
http://127.0.0.1:8000/password-reset/
2.1.3
SMTPSenderRefused
(530, b'5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/mail/?p=WantAuthError p2sm3089174pfp.125 - gsmtp', 'webmaster@localhost')
c:\users\mickey\appdata\local\programs\python\python37\Lib\smtplib.py in sendmail, line 867
F:\webwork\Django\Test\MyEnv\Scripts\python.exe
3.7.1
['F:\webwork\Django\madhatterlast', 'F:\webwork\Django\Test\MyEnv\Scripts\python37.zip', 'F:\webwork\Django\Test\MyEnv\DLLs', 'F:\webwork\Django\Test\MyEnv\lib', 'F:\webwork\Django\Test\MyEnv\Scripts', 'c:\users\mickey\appdata\local\programs\python\python37\Lib', 'c:\users\mickey\appdata\local\programs\python\python37\DLLs', 'F:\webwork\Django\Test\MyEnv', 'F:\webwork\Django\Test\MyEnv\lib\site-packages']
Thu, 13 Dec 2018 15:36:06 +0000

Looking forward to hearing from you.
Thanks.

@miguelgrinberg
Copy link
Owner

@mickey911112 this repo is a Flask project, you may need to ask in a Django community for specific information about your case, but in any case, the error is about not providing valid credentials for your Google account.

@RWSmax
Copy link

RWSmax commented Jun 5, 2019

Hi, this problem is solvable.
Why set MAIL_USERNAME = None.
In this code:
(venv)$set MAIL_USERNAME = 'name example'
(venv)$set MAIL_PASSWORD = 'password example'
(venv)$pythonhello.py shell

from flask_mail import Message
from hello import mail
msg = Message('TEXT', sender = 'my1@example.com', recipients = 'my2@example.com') #not important
msg.body = 'text_body'
msg.html = 'html_body'
with app.app_context():
... mail.send(msg)
...`

SMTPSenderRefused at /info/(530, b'5.5.1 Authentication Required. Learn more at\n5.5.1.....
But look at this:

print(app.config)

and i see MAIL_USERNAME = None, MAIL_PASSWORD = None and etc.(where the hell is she? at was in 1 session cmd)
had to specify in app.config clear option without the os.environ.get('MAIL_USERNAME')
The problem many people with this error is that:
With each cmd session my set MAIL_USERNAME and etc. disappear

brain boils..
p.S
(venv)$set MAIL_USERNAME
return this:
MAIL_USERNAME environment variable not defined


Need create an environment variable(MAIL_USERNAME and etc) in System Properties!

@KathiravanBalasubramanian

Hi all,

I faced the same.
Environment : Windows, Python version: 3.7.4

Below are the steps i followed to fix it

1, I set the environment variables using the edit system environment variables option in control panel.
2, I checked whether they were set properly by running the below commands in cmd and they were fine.

echo %EMAIL_USER%
echo %EMAIL_PASS%

3, I checked whether i am fetching the proper data from inside the python vm by running the below commands in the interpreter
import os
os.environ.get('EMAIL_USER')
os.environ.get('EMAIL_PASS')

4, Added another check point while initializing the flask app in init.py

print(f"For SMT Mail: username:{os.environ.get('EMAIL_USER')}, password:{os.environ.get('EMAIL_PASS')} ")

5, When i run the application inside terminal from visual studio code the values were not being set properly
For SMT Mail: username:None, password:None

6, When i run the same from a cmd outside vs code the environment variables were set properly and email function worked as expected.

**For SMT Mail: username:***, password:

Further more as @RWSmax explains when you set the environment variable in cmd it applies right there and then, to that process' environment. Also when you open a new terminal or cmd it will get a copy of the current environment from it's parent so you would have to restart the process in order to get a new set of environment variables.

Its basically was about setting the environment variables properly and also wrt how you are setting the environment variables. At the end Step 4 would give you the verdict.

@emit077
Copy link

emit077 commented Apr 23, 2020

Hey !
i got the error in the simple SMTP setup in the Django project for sending email
but i don;t know why its not acception it

(535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials c1sm3161260pfc.94 - gsmtp')

@HarshitBagla
Copy link

HarshitBagla commented Apr 23, 2020 via email

@KhandelwalAayush
Copy link

i got this error please help me out from this error

smtplib.SMTPSenderRefused
smtplib.SMTPSenderRefused: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError y12sm8799858pfo.182 - gsmtp', 'noreply@demo.com')

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'] = os.environ.get('EMAIL_USER')
app.config['MAIL_PASSWORD'] = os.environ.get('EMAIL_PASS')
mail = Mail(app)

please check what's wrong here....

@miguelgrinberg
Copy link
Owner

@KhandelwalAayush did you set your username and password in the environment variables? The error says you are not providing authentication.

@KhandelwalAayush
Copy link

KhandelwalAayush commented Jun 29, 2020

@miguelgrinberg where i have to set user name and password in the EV and which id password, i have to provide please explain in briefly

@miguelgrinberg
Copy link
Owner

@KathiravanBalasubramanian this is covered in detail in the book that goes along with this repository. If you are not following the tutorial, then see the Flask-Mail documentation to learn how to set up your credentials.

@KhandelwalAayush
Copy link

@miguelgrinberg
not getting anything in the Flask Documentation please explain...

@miguelgrinberg
Copy link
Owner

@KhandelwalAayush the username and password go in environment variables, but as I said, this may not make much sense to you if you are not following the book. Read the Flask-Mail documentation if you want more general instructions on how to send email.

@KhandelwalAayush
Copy link

@miguelgrinberg Now i set the user name and password in the E.V. and also allow the less secure app but still coming the same error.....please help

**smtplib.SMTPSenderRefused
smtplib.SMTPSenderRefused: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError d5sm159706pjo.20 - gsmtp', 'flask@example.com')

Traceback (most recent call last)
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 2464, in call
return self.wsgi_app(environ, start_response)
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask_compat.py", line 39, in reraise
raise value
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask_compat.py", line 39, in reraise
raise value
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functionsrule.endpoint
File "F:\Flask_Blog\flaskblog\routes.py", line 180, in reset_request
send_reset_email(user)
File "F:\Flask_Blog\flaskblog\routes.py", line 170, in send_reset_email
mail.send(msg)
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask_mail.py", line 492, in send
message.send(connection)
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask_mail.py", line 427, in send
connection.send(self)
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask_mail.py", line 188, in send
self.host.sendmail(sanitize_address(envelope_from or message.sender),
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\Lib\smtplib.py", line 871, 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 d5sm159706pjo.20 - gsmtp', 'flask@example.com')
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.

You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:

dump() shows all variables in the frame
dump(obj) dumps all that's known about the object**

@HarshitBagla
Copy link

HarshitBagla commented Jul 2, 2020 via email

@Divyansh-Purohit
Copy link

@miguelgrinberg Sir, I've correctly assigned the mail username and password in a python shell using the os.environ['PROPERTY'], also enabled 'Less secure apps' from the settings of my google account, but still I'm getting SMTPSenderRefused Error. If you could please help me.....I've gone through the above issues faced by the other users and read your replies. According to me everything is fine in my code and according to the book.
Capture

@miguelgrinberg
Copy link
Owner

assigned the mail username and password in a python shell using the os.environ['PROPERTY']

What do you mean? You have to set environment variables in your shell.

@Divyansh-Purohit
Copy link

Divyansh-Purohit commented Sep 7, 2020 via email

@Divyansh-Purohit
Copy link

Divyansh-Purohit commented Sep 7, 2020 via email

@pintuprajapati
Copy link

Hi all,

I faced the same. Environment : Windows, Python version: 3.7.4

Below are the steps i followed to fix it

1, I set the environment variables using the edit system environment variables option in control panel. 2, I checked whether they were set properly by running the below commands in cmd and they were fine.

echo %EMAIL_USER% echo %EMAIL_PASS%

3, I checked whether i am fetching the proper data from inside the python vm by running the below commands in the interpreter import os os.environ.get('EMAIL_USER') os.environ.get('EMAIL_PASS')

4, Added another check point while initializing the flask app in init.py

print(f"For SMT Mail: username:{os.environ.get('EMAIL_USER')}, password:{os.environ.get('EMAIL_PASS')} ")

5, When i run the application inside terminal from visual studio code the values were not being set properly For SMT Mail: username:None, password:None

6, When i run the same from a cmd outside vs code the environment variables were set properly and email function worked as expected.

**For SMT Mail: username:***, password:

Further more as @RWSmax explains when you set the environment variable in cmd it applies right there and then, to that process' environment. Also when you open a new terminal or cmd it will get a copy of the current environment from it's parent so you would have to restart the process in order to get a new set of environment variables.

Its basically was about setting the environment variables properly and also wrt how you are setting the environment variables. At the end Step 4 would give you the verdict.

This really really helped me. Thank you very much. spent so many hours but could not find the answer. finally got it. I have gone step by step and set the variables into environment. Closed the vs code terminal and started using in CMD. ran the command and it worked.
I will write the whole answer with my screenshots and what I did.

@pintuprajapati
Copy link

pintuprajapati commented May 18, 2022

Hi all,

I faced the same. Environment : Windows, Python version: 3.7.4

Below are the steps i followed to fix it

1, I set the environment variables using the edit system environment variables option in control panel. 2, I checked whether they were set properly by running the below commands in cmd and they were fine.

echo %EMAIL_USER% echo %EMAIL_PASS%

3, I checked whether i am fetching the proper data from inside the python vm by running the below commands in the interpreter import os os.environ.get('EMAIL_USER') os.environ.get('EMAIL_PASS')

4, Added another check point while initializing the flask app in init.py

print(f"For SMT Mail: username:{os.environ.get('EMAIL_USER')}, password:{os.environ.get('EMAIL_PASS')} ")

5, When i run the application inside terminal from visual studio code the values were not being set properly For SMT Mail: username:None, password:None

6, When i run the same from a cmd outside vs code the environment variables were set properly and email function worked as expected.

**For SMT Mail: username:***, password:

Further more as @RWSmax explains when you set the environment variable in cmd it applies right there and then, to that process' environment. Also when you open a new terminal or cmd it will get a copy of the current environment from it's parent so you would have to restart the process in order to get a new set of environment variables.

Its basically was about setting the environment variables properly and also wrt how you are setting the environment variables. At the end Step 4 would give you the verdict.

whoever is reading, highly recommended to follow the steps above mentioned by @KathiravanBalasubramanian. I did the same and changed somethings and it worked.
Note: I was making projects in Django (not in flask) but it will work I think
My steps:

  1. First I added my Gmail ID and password to environment variable.

image

  1. (Also allowed "Less secure app access" in Gmail account)

  2. Changed my settings.py to this
    ## for account email varification

import os
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.environ.get('EMAIL_USER')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS')`

  1. In my emails.py file (I have made separate file for this)

## Email varification for account

def send_account_activation_email(email, email_token):
subject = 'Account varificaion email'
email_from = settings.EMAIL_HOST_USER

  1. This problem occurred into VS CODE terminal. so I closed it and tried to run into CMD. Performed above steps (mentioned by @KathiravanBalasubramanian) to check whether my EMAIL ID and PASSWORD are set properly or not. And in CMD I could see the correct email id and password.

  2. After step 4 was confirmed, I ran the project and it worked. I hope it helps.

@Seek-Techs
Copy link

def generate_confirmation_token(self, expiration=3600):
s = Serializer(current_app.config['SECRET_KEY'], str(expiration))
# return s.dumps({'confirm': self.id}).decode('utf-8')
return s.dumps({'confirm': self.id})
def confirm(self, token):
s = Serializer(current_app.config['SECRET_KEY'])
# def generate_confirmation(self):
# s = TimedSerializer(current_app.config['SECRET_KEY'], 'confirmation')
# return s.dumps(self.id)

# def check_confirmation(self, token, max_age=3600):
#     s = TimedSerializer(current_app.config['SECRET_KEY'])
    # s = TimedSerializer(current_app.secret_key, 'confirmation')
    
    try:
        data = s.loads(token.encode('utf-8'))
    except:
        return False
    if data.get('confirm') != self.id:
        return False
    self.confirmed = True
    db.session.add(self)
    return True
The above lines of code gives me confirmation link invalid or expired, please explain to me how I can solve it.

Capture2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests