I am new in Django. I am trying to add a feature in my project that enables user to reset his password through given email. These configurations are in development and not production. This is my configuration in settings.py
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')
I tried these but nothing seems to be working. I enabled IMAP from gmail settings as well.
Can you please help me what am I doing wrong in here!
In case if you want to see full error.
SMTPAuthenticationError at /password-reset/ (535, b'5.7.8 Username and
Password not accepted.
https://support.google.com/mail/?p=BadCredentials a24sm3958276ljd.32 -
gsmtp')
URL: http://localhost:8000/password-reset/
Exception Type: SMTPAuthenticationError
b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8
https://support.google.com/mail/?p=BadCredentials a24sm3958276ljd.32 -
gsmtp') Exception
Location: C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\smtplib.py
in auth, line 642 Python
Executable: C:\Users\Administrator\AppData\Local\Programs\Python\Python37\python.exe
Python Version: 3.7.2 Python Path:
['C:\Users\Administrator\Desktop\django_project',
'C:\Users\Administrator\AppData\Local\Programs\Python\Python37\python37.zip',
'C:\Users\Administrator\AppData\Local\Programs\Python\Python37\DLLs',
'C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib',
'C:\Users\Administrator\AppData\Local\Programs\Python\Python37',
'C:\Users\Administrator\AppData\Roaming\Python\Python37\site-packages',
'C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages']
Server time: Thu, 4 Apr 2019 12:24:22 +0000Learn more at\n5.7.8Request Method: POST RequestDjango Version: 2.1.7Exception Value: (535,
Would you mind double checking if your environment variables are set correctly? Also, did you enable this feature on your Google account: https://www.google.com/settings/security/lesssecureapps?
Take a look at this answer, as it might help you as well: SMTPAuthenticationError when sending mail using gmail and python
In my case it was working on my local machine but not on heroku server. I went on this link https://accounts.google.com/DisplayUnlockCaptcha
and clicked on Continue. After that I had to re-login into my gmail account. It started working. Hope it might help someone!
Feb, 2022 Update:
You need to do 2 things to get over very strong google's security.
Allow less secure apps: ON ↓↓↓
https://myaccount.google.com/lesssecureapps
Allow access to your Google account: ON (Tap "Continue") ↓↓↓
https://accounts.google.com/DisplayUnlockCaptcha
Related
When trying to login into a Gmail account using SMTP, this error message occurs:
SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted.
Code causing the error:
import smtplib
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login("sending#gmail.com", "your_password")
message = "TEST"
server.sendmail("sending#gmail.com", "receiving#gmail.com", message)
server.quit()
Google has disabled the ability to enable less secure apps as of May 2022. Because of this, the previous solution of enabling less secure apps is no longer valid.
Steps:
Go into your sending email address and make your way to the settings.
Find two-step authentication and enable it.
Under two-step authentication there should be a tab labeled App passwords. Click on it then select mail as the app and your device of choice
Use the password generated from the app password as the password for your Gmail account.
Credits to: Link to source
I am trying to send emails with G-Suite account using python in Django. As Google stoped the less secure App option for the new applications, I have to use Oauth2.
But when I start to send emails via smtplib, the ERROR:
smtplib.SMTPSenderRefused: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError q4sm8418287pfl.175 - gsmtp'
And after looking up the reference, it means "530, "5.7.0", Must issue a STARTTLS command first."
However, I have added "server.starttls()". Could someone help me? Many thanks.
server = smtplib.SMTP('smtp.gmail.com', port=587)
server.ehlo('test')
server.starttls()
server.docmd('AUTH', 'XOAUTH2 ' + base64.b64encode(auth_string.encode()).decode("utf-8"))
server.sendmail(from_addr, to_addr, msg.as_string())
server.quit()
Per this https://stackabuse.com/how-to-send-emails-with-gmail-using-python/#:~:text=As%20for%20the%20actual%20Python,com'%2C%20465)%20server., you probably have 2-step verification turned on.
To enable your web apps to send SMTP's from/to your gmail, you will need to create an app-specific password for less secure apps.
Go to your Google Account.
Select Security.
Under "Signing in to Google," select App Passwords. You may need to
sign in. If you don’t have this option, it might be because: 2-Step
Verification is not set up for your account. 2-Step Verification is
only set up for security keys. Your account is through work, school,
or other organization. You turned on Advanced Protection.
At the bottom, choose Select app and choose
the app you are using and then Select device and choose the device
you’re using and then Generate.
Take this 16-character code in the yellow bar and place it in your
environment variables as your "EMAIL_HOST_PASSWORD"
EMAIL_BACKEND="django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST_USER ='youremail#gmail.com'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_PASSWORD = 'yourpassword'
EMAIL_USE_TLS = True
Add this on your settings. After that :
python manage.py shell
You will enter to Python shell. Then:
from django.core.mail import send_mail
Write this command on shell and after that:
send_mail(
"django test mail",
"this is django test mail",
"your.email#gmail.com",
"recipient.email#example.com",
fail_silently=False
)
If output is equal to:
1
, then you send email through your Gmail.
I'm trying to send an e-mail from django app in docker on Ubuntu and I'm receiving following message:
Request Method: GET
Request URL: https://localhost:8001/accounts/mail/
Django Version: 2.2.5
Exception Type: SMTPAuthenticationError
Exception Value:
(535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials x76sm1225174ljb.81 - gsmtp')
Exception Location: /usr/local/lib/python3.7/smtplib.py in auth, line 642
Python Executable: /usr/local/bin/python
Python Version: 3.7.4
There is no problem to send an e-mail outside docker.
I tried every step from Google troubleshooting steps. Currently I have 2-Step verification which works for local app but still doesn't for docker one.
I don't necessarily need Google SMTP (I have an account there), but what I what to achive is to send e-mail with activation link to user after registration for django application.
I tried without 2-factor auth - the same result. My docker-compose settings in web service:
services:
web:
build: ./app
command: python manage.py runsslserver 0.0.0.0:8001
stdin_open: true
tty: true
volumes:
- ./app/:/usr/src/app/
- /etc/localtime:/etc/localtime
- /etc/timezone:/etc/timezone
ports:
- 8001:8001
- 587:587
- 25:25
- 465:465
And code to send an e-mail (works outside the docker):
def email(request):
mail_subject = 'Activate your account'
message = 'test'
to_email = 'example#example.com'
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
return redirect('index')
settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'example#example.com'
EMAIL_HOST_PASSWORD = '***'
EMAIL_PORT = 587
Problem solved! I've applied different code for sending e-mail.
import smtplib
import ssl
def email(request):
port = settings.EMAIL_PORT
smtp_server = settings.EMAIL_HOST
sender_email = settings.EMAIL_HOST_USER
password = settings.EMAIL_HOST_PASSWORD
receiver_email = 'example#example.com'
subject = 'Website registration'
body = 'Activate your account.'
message = 'Subject: {}\n\n{}'.format(subject, body)
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
return redirect('index')
I'm still wondering if this is the right way to pass variables from django settings. Am I doing it in elegant way and is it necessary? And is it the best way for smtp?
Another potential solution is posted here.
I used Flask but the error was exactly the same. I made sure that my credentials were correct and the environment variables were not enclosed in quotes like this post suggested.
The short answer from the first post is to click this link while logged into the google account associated with the gmail you're sending from.
Google doesn't trust most programs to automatically login to your account, so they put the onus on the owner of the gmail to give "less secure apps" permission to access your gmail.
I solved this problem by enabling less secure apps on the host Gmail account.
Go Gmail security option and then: Allow less secure apps: ON
After 30 May 2022 less secure apps solution is not working. because google stopped supporting less secure apps link
Solution
so you need to set up the App Password from setting.
This video shows
how to set up App Password.
I'm trying to send a simple email using python/django shell and have been strugling with this problem for the last few hours:
in django shell i do the following:
from django.core.mail import send_mail
send_mail('django mail', 'this was sent with django', 'myaddress#gmail.com',['myaddress#gmail.com'], fail_silently=False)
the returned result should be 1, meaning that the mail is sent successfully, but insead, i get this:
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbu9\n5.7.14 0cv5jjPsAITCLvsSIKoDuJcz5I18H7PMX8Nsxz2ajtgAJfxls4wIKIVMUENCrFmoXNHdgM\n5.7.14 NpSKlFYuaGHtwqDodV09jIf_GaDklCUUzJLY7oSJITQqXADDWxYRU7LUbVRFPxwpd2cKzl\n5.7.14 g70grCboTaCtEofq3-5edwoRC0ukZT-z97AgOelTTvSteaEjuf5n7F417VvFFE1hXcBnyg\n5.7.14 n2NWXBFMlV_74532aXU0vguceCC84> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 2sm2181268wrn.24 - gsmtp')
I read the url suggested in the error, and also a few similar questions on the web, and there were no good it them for me.
also, in the settings.py file, the required code is included:
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'me#gmail.com'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_PORT = 587
as i mentioned above, the other questions/problems on this site weren't the same. I've already enable the access for less secure apps on my gmail account, and also i have no two step verification.
IIRC to send email using gmail SMTP from third-party apps (your own Django app), you need to enable what they call Less Secure Apps.
You can read more here: https://support.google.com/accounts/answer/6010255
The app configuration used in a Flask Mail application (following Miguel Grinberg Flask developlemt book) :
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('MAIL_USERNAME')
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
The Mail Username and Password variables have been set correctly and rechecked. While trying to send a message using the following code,
from flask.ext.mail import Message
from hello import mail
msg = Message('test subject', sender='same as MAIL_USERNAME', recipients=['check#mail.com'])
msg.body = 'text body'
msg.html = '<b>HTML</b> body'
with app.app_context():
mail.send(msg)
While sending, the application is again and again resulting in the following error:
SMTPSenderRefused: (530, '5.5.1 Authentication Required. Learn more at\n5.5.1 http://support.google.com/mail/bin/answer.py?answer=14257 qb10sm6828974pbb.9 - gsmtp', u'configured MAIL_USERNAME')
Any workaround for the error?
While digging into the issues faced, I rechecked the SMTP settings for Google,
Changing the
app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
to
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
did the trick.
Also make sure that the full username is used as Gmail SMTP username, i.e., example#gmail.com as shown in the image above.
Hope this helps!!!
I also followed this book and get the same problem, after some digging here and there, I found out the root cause of the problem. However, I am not sure whether it will be the same case for you or not.
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
As you can see your flask app gets the your email credentials through os.environ.get(), and if you set this environment variables temporarily in your system, in my case Mac OSX, after your terminal session they will be gone, so you need to set them again for the next time you enter the terminal, like below:
export MAIL_USERNAME=**YOUR EMAIL**
export PASSWORD=**YOUR PASSWORD**
I got this error because of this scenario, in order to set them permanently you need to include these variables into .bash_profile file in your home directory.
You need to change your Google account settings. On this page, turn on the option to "Allow less secure apps".
As that page says:
Some apps and devices use less secure sign-in technology, which makes your account more vulnerable. You can turn off access for these apps, which we recommend, or turn on access if you want to use them despite the risks. Learn more
Do these 2 things to resolve:
Use this link and turn on 'Allow less secure apps'- https://myaccount.google.com/lesssecureapps
Use hard-coded value for email and password and it worked fine.
Simply in the file 'init.py', edit the following section:
Don't use os.environ.get
app.config['MAIL_USERNAME'] = 'youremail#gmail.com'
app.config['MAIL_PASSWORD'] = 'yourpassword'