Login credentials not working with Gmail SMTP
Asked Answered
K

20

165

I am attempting to send an email in Python, through Gmail. Here is my code:

import smtplib

fromaddr = '......................'  
toaddrs  = '......................'  
msg = 'Spam email Test'  
      
username = '.......'  
password = '.......'

server = smtplib.SMTP('smtp.gmail.com', 587)  
server.ehlo()
server.starttls()
server.login(username, password)  
server.sendmail(fromaddr, toaddrs, msg)  
server.quit()

I get the error:

Traceback (most recent call last):
  File "email_send.py", line 18, in <module>
    server.login(username, password)
  File "C:\.....\Python\lib\smtplib.py", line 633
, in login
    raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepte
d. Learn more at\n5.7.8 http://support.google.com/mail/bin/answer.py?answer=1425
7\n5.7.8 {BADCREDENTIALS} s10sm9426107qam.7 - gsmtp')

This seems to be a problem with the login. I am certain that my login details are correct, except for one thing. Should username be "[email protected]", or simply "blah"? I tried both, same error.

Any idea whats wrong?

NOTE: all the periods are instead of password/email/file paths/etc.

Kellie answered 12/5, 2013 at 22:16 Comment(6)
On support.google.com/mail/answer/14257 possible issue can be captcha or other type of verification process that needs user interaction. Have you tried to login normally?Unmeaning
Exactly, Gmail is very unstable for sending mail through code, I experienced lots of problems when sending email from python code through gmail accounts, Yahoo accounts on the other hand work very good.Beatrizbeattie
#16203571Beatrizbeattie
Your code works with my [email protected]. If I send wrong username or password I get the same error.Ringdove
Use this link and turn on this option by logging in your desired email. myaccount.google.com/lesssecureapps Thanks.Burlie
@Shawnock Guha Paul I fought with this for a long time. Thanks!Hoffman
V
329

UPDATE: This feature is no longer supported as of May 30th, 2022. See https://support.google.com/accounts/answer/6010255?hl=en&visit_id=637896899107643254-869975220&p=less-secure-apps&rd=1#zippy=%2Cuse-an-app-password

ORIGINAL ANSWER (No longer working): I ran into a similar problem and stumbled on this question. I got an SMTP Authentication Error but my user name / pass was correct. Here is what fixed it. I read this:

https://support.google.com/accounts/answer/6010255

In a nutshell, google is not allowing you to log in via smtplib because it has flagged this sort of login as "less secure", so what you have to do is go to this link while you're logged in to your google account, and allow the access:

https://www.google.com/settings/security/lesssecureapps

Once that is set (see my screenshot below), it should work.

Less Secure Apps

Login now works:

smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login('[email protected]', 'me_pass')

Response after change:

(235, '2.7.0 Accepted')

Response prior:

smtplib.SMTPAuthenticationError: (535, '5.7.8 Username and Password not accepted. Learn more at\n5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 g66sm2224117qgf.37 - gsmtp')

Still not working? If you still get the SMTPAuthenticationError but now the code is 534, its because the location is unknown. Follow this link:

https://accounts.google.com/DisplayUnlockCaptcha

Click continue and this should give you 10 minutes for registering your new app. So proceed to doing another login attempt now and it should work.

This doesn't seem to work right away you may be stuck for a while getting this error in smptlib:

235 == 'Authentication successful'
503 == 'Error: already authenticated'

The message says to use the browser to sign in:

SMTPAuthenticationError: (534, '5.7.9 Please log in with your web browser and then try again. Learn more at\n5.7.9 https://support.google.com/mail/bin/answer.py?answer=78754 qo11sm4014232igb.17 - gsmtp')

After enabling 'lesssecureapps', go for a coffee, come back, and try the 'DisplayUnlockCaptcha' link again. From user experience, it may take up to an hour for the change to kick in. Then try the sign-in process again.

UPDATE:: See my answer here: How to send an email with Gmail as provider using Python?

Villus answered 16/12, 2014 at 23:31 Comment(8)
I have enabled it for less secure devices, but then also login doesn't seem to work for me. Is there any other thing else in which changes are to be madeRudder
This is true also for other email services. I had the same issue with Yahoo. So, be sure to have this option ENABLED, of your script, bot, etc., will not work.Whoops
This is also because when you're not using your gmail after turning ENABLED google automatically turns it off.Mcelroy
Allowing "lesssecureapps" enables using smtp. Works after flipping the switch. Upvoted !Woodshed
It's outdated. Google is not supporting this feature anymore! support.google.com/accounts/answer/…Masculine
This no longer works. You need to do what OmG has posted about creating an "App Password". That worked for me!Aerothermodynamics
The solution mentioned down below about "App password" is the new solution!Chant
Still works, create an app password by following the steps under section "Create & use app passwords" here: support.google.com/accounts/answer/185833Camise
L
69

I am also faced with the same error message when I try to use smtplib. The error message was like this;

error (535, b'5.7.8 username and password not accepted.

Google has changed access to less secure apps. Before that, there was a field to give access to. Now you can follow these steps;

The steps have changed slightly

  1. Go to Google Account Page>Security>Signing in to Google section turn on 2-Step Verification. You need this feature on.

First Step

  1. When 2SV is on, click 2-Step Verification, scroll to the bottom to App Password.

Second Step

  1. Generate new-app-password for mail access. It will generate it for you, then use this password in gmail_password function in Python.

    gmail_password='google_generate_it_for_you'

Third step

Lauber answered 23/6, 2022 at 17:36 Comment(7)
This is the most up to date answer, and the best one in my opinion.Forewoman
I'm writing a script for an automation tool I'm building in python using the smtplib library and set up a password, but it still does not work.Opuntia
@KevinG when you create a password you should select specific app and device. If its not match when you test, it will give you an error probably.Lauber
I got it setup, I had the wrong variable set for my password. Thanks!Opuntia
Let's upload this answer, this one is more up to date.Saccharine
Thanks a mill. This worked for me using yagmail. Literally replaced where I had my gmail password before, and replaced with the new app password: yag = yagmail.SMTP(from_, password='app password goes here')Gerome
Most simple to follow and upto date answer. Have been trying to find a solution for so long. Thank you so muchOrme
L
48

I had the same issue. The Authentication Error can be because of your security settings, the 2-step verification for instance. It wont allow third party apps to override the authentication.

  1. Log in to your Google account

  2. Disable 2-step verification: https://myaccount.google.com/security?utm_source=OGB&utm_medium=act#signin

  3. Allow less secure apps: https://myaccount.google.com/u/1/lesssecureapps?pli=1&pageId=none

It should be all good now.

Legatee answered 12/2, 2018 at 20:58 Comment(1)
This also works! we just need to do Step 2 cause google automatically brings the less secure apps to off if we don't use much the google account.Mcelroy
B
21

If you're using smtp.gmail.com, then you have to do the following:

  1. Turn on the less secure apps

  2. You'll get the security mail in your gmail inbox, Click 'Yes,it's me' in that.

  3. Now run your code again.

Bugeye answered 20/11, 2019 at 5:11 Comment(1)
"less secure apps" has been removed by Google since May 2022.Inseminate
M
15

Denied

The solution of using "Access for the less secure app" in Gmail has been denied (find more here).

Update

By the way, you can get access to the gmail account by the solution proposed by Google, called "App password". The solution is simple:

1. Active two-step verification of the corresponding account.
2. Create an app password. 
3. Exactly do the same implementation that you have for sending an email (explained in your question). 
   Except, replace the password with the generated app password (a sixteen digit password).

For more details you can also follow this post (it's working well for me).

Masculine answered 2/6, 2022 at 11:56 Comment(2)
This didn't work entirely for me. I still got the same error. However, if you do some minor changes to the procedure in the article attached above you should be fine: When enabling the App Password choose Mail instead of Other for which app to select and choose "you computer" (the device in which the code is being executed) under devices instead of Other.Playlet
@PrebenAndersen BTW, I'm using the same suggested scenario, and it's working well. To resolve your problem, you can share the error that you got.Masculine
C
12

I had same issue. And I fix it with creating an app-password for Email application on Mac. You can find it at my account -> Security -> Signing in to Google -> App passwords. below is the link for it. https://myaccount.google.com/apppasswords?utm_source=google-account&utm_medium=web

Clere answered 11/2, 2019 at 7:17 Comment(1)
Note: You have to enable App Passwords if you have MFA on. I had to go to my administrator account: admin.google.com -> security -> less secure enable. Then I had to go to my personal account: security -> App Passwords. Then I could run a TLS connection & send an email.Frederiksen
C
7

If you turn-on 2-Step Verification, you need generate a special app password instead of using your common password. https://myaccount.google.com/security#signin

Chemash answered 18/3, 2017 at 13:54 Comment(1)
This is usually better than disablin' less secure apps because of security reasons, but they're complex so you can't remember them, this means either you have to like write it in a comment and erase it before publishing the final product or maybe store it in a databaseLowestoft
W
7

if you are getting error this(535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials o60sm2132303pje.21 - gsmtp')

then simply go in you google accountsettings of security section and make a less secure account and turn on the less secure button

Wasteland answered 27/9, 2019 at 7:20 Comment(1)
Less secure app access Some apps and devices use less secure sign-in technology, which makes your account vulnerable. You can turn off access for these apps, which we recommend, or turn it on if you want to use them despite the risks. Google will automatically turn this setting OFF if it’s not being used. Learn more Allow less secure apps: ONWasteland
N
4

I had the same issue , i solved this by allowing "less secure app access" . This can be found in Security tab on Google Account: enter image description here

Narcosynthesis answered 18/11, 2021 at 21:36 Comment(1)
@Jamjitul It does answer the question wel as you might have noticedNarcosynthesis
H
2

Apparently google has changed the setting. So as of "September, 2023", what you have to do is, follow these steps:

  1. Go to your account settings and find the "Security" option.
  2. Enable 2-step authentication
  3. Now you will see an option "App Password". Create app password from there. It will be of 16 digits
  4. Copy paste the app password and use it instead of your google password for your smtp.

********************** Important*******************

The two important things to make sure after that are (which might be causing errors):

  1. When you will directly copy paste the app password, there would be spaces in it for example "abcd efgh ijkl lmno". SO make sure to remove the spaces and use it as "abcdefghijkllmno"
  2. For example If your gmail account is "[email protected]" then your username would be "abcd123" and not "[email protected]". So make sure to use "abcd123" for the 'username' argument in server.login(). So your server.login(username, password) would look like server.login("abcd123", "abcdefghijkllmno")

I hope it solves

Hoggish answered 29/9, 2023 at 8:26 Comment(0)
C
1

Dec, 2022 Update:

You need to use an app password to allow your app to access your google account.

So, you need to:

  1. generate an app password following my answer explaining how to generate an app password.

  2. assign the generated app password to password in your code as shown below:

import smtplib

fromaddr = '......................'  
toaddrs  = '......................'  
msg = 'Spam email Test'  

username = '.......'  
password = 'xylnudjdiwpojwzm' # Here

server = smtplib.SMTP('smtp.gmail.com', 587)  
server.ehlo()
server.starttls()
server.login(username, password)  
server.sendmail(fromaddr, toaddrs, msg)  
server.quit()
Cavil answered 30/11, 2022 at 3:10 Comment(0)
I
1

Update after May 30th, 2022 :

  1. To solve this problem it is necessary to activate two-step verification on your Gmail account :

https://myaccount.google.com/u/1/security

  1. Then you will have access to a new page to create an App Password :

https://myaccount.google.com/u/1/apppasswords

Finally, using this password on your django application should solve the problem.

Tutorial for more information: https://www.youtube.com/watch?v=sCsMfLf1MTg

Interstratify answered 29/12, 2022 at 10:42 Comment(1)
That answer has already been given and upvoted 6 months ago.Proliferous
P
0
  1. Enable 2FA for your Google account
  2. Then set an app password for your app
  3. Use that new password
Patrol answered 2/7, 2022 at 17:27 Comment(1)
Thanks! Google will generate a new password, you have to use that in order to use SMTP, IMAP, and must select proper app otherwise this won't work.Titleholder
D
0

For email created by G-Suite or Google Workspace, you have to ask your admin to activate the Gmail app and assigned it to your email account. Without this step, trying either above methods still does not work.

Deery answered 3/8, 2022 at 13:39 Comment(0)
I
0

Oct 3 2022

As per all the answers mentioned above. Enabling 2Factor Authentication and creating an App Pasword does the trick with SMTP.

NOTE: Less secure apps toggle doesn't work anymore tbh?(Others confirm?)

Inoperable answered 3/10, 2022 at 16:36 Comment(0)
T
0

less secure apps can now only be used in gmail if you turn on 2 factor auth and then generate an app password for a custom app

these steps worked for me :) follow these steps https://myaccount.google.com/security

Toluol answered 9/1, 2023 at 17:28 Comment(0)
F
0

It is no longer possible as google has removed support for Less secure apps.

However you can still use App Passwords

Documentation from google -https://support.google.com/accounts/answer/185833?hl=en

Create & use App Passwords

If you use 2-Step-Verification and get a "password incorrect" error when you sign in, you can try to use an App Password.

    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 using and then Select device and choose the device you’re using and then Generate.
    Follow the instructions to enter the App Password. The App Password is the 16-character code in the yellow bar on your device.
    Tap Done.

Tip: Most of the time, you’ll only have to enter an App Password once per app or device, so don’t worry about memorizing it.
Foxhound answered 9/2, 2023 at 6:52 Comment(0)
R
0

Less secure app access makes your account vulnerable. Google has removed support for it

App passwords aren’t recommended and are unnecessary in most cases. To help keep your account secure, use "Sign in with Google" to connect apps to your Google Account.

Working

Use app passwords

  1. To solve this problem it is necessary to activate two-step verification on your Gmail account : 2-step Verification(google)

  2. Then you will have access to a new page to create an App Password: Generate App-password

After use generate app password. Use in your project using your in place of password while using smtp protocol in python to get it working.

Rhett answered 17/9, 2023 at 4:26 Comment(0)
T
-1

In my case, I allowed the access, but the problem was that I was using server.login('Name <email>', password). Please, make sure to use only your email here: server.login('[email protected]', password).

Response after change:

(235, '2.7.0 Accepted')

Response prior:

smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8  https://support.google.com/mail/?p=BadCredentials 130sm13119106qkh.99 - gsmtp')
Teets answered 7/10, 2021 at 4:57 Comment(0)
H
-2

Try turning on less secure apps and make sure that you have smtp.gmail.com or for different search up

Hafiz answered 24/5, 2021 at 19:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.