164

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 "blah@gmail.com", or simply "blah"? I tried both, same error.

Any idea whats wrong?

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

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Jacob Kudria
  • 2,200
  • 3
  • 17
  • 18
  • 1
    On https://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? – Robert Lujo May 12 '13 at 22:50
  • 3
    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. – PepperoniPizza May 12 '13 at 23:06
  • 1
    http://stackoverflow.com/questions/16203071/sending-emails-in-python-weird-behaviour – PepperoniPizza May 12 '13 at 23:08
  • 3
    Your code works with my username@gmail.com. If I send wrong username or password I get the same error. – Txema May 14 '13 at 13:21
  • 1
    Use this link and turn on this option by logging in your desired email. https://myaccount.google.com/lesssecureapps Thanks. – Shawnock Guha Paul May 04 '21 at 20:22
  • @Shawnock Guha Paul I fought with this for a long time. Thanks! – Lenn Dolling Oct 11 '22 at 18:38

18 Answers18

325

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('me@gmail.com', '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?

radtek
  • 34,210
  • 11
  • 144
  • 111
  • 1
    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 made – proprius Feb 04 '16 at 11:22
  • 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. – ivanleoncz Mar 28 '19 at 18:16
  • This is also because when you're not using your gmail after turning `ENABLED` google automatically turns it off. – Ice Bear Dec 22 '20 at 07:03
  • Allowing "lesssecureapps" enables using smtp. Works after flipping the switch. Upvoted ! – Simplicity's_Strength May 27 '21 at 23:22
  • 7
    It's outdated. Google is not supporting this feature anymore! https://support.google.com/accounts/answer/6010255?hl=en&visit_id=637896899107643254-869975220&p=less-secure-apps&rd=1#zippy=%2Cuse-an-app-password – OmG Jun 01 '22 at 14:20
  • 2
    This no longer works. You need to do what OmG has posted about creating an "App Password". That worked for me! – oriuken Jun 17 '22 at 14:47
  • 2
    The solution mentioned down below about "App password" is the **new** solution! – ArtixZ Aug 02 '22 at 21:26
  • Still works, create an app password by following the steps under section "Create & use app passwords" here: https://support.google.com/accounts/answer/185833 – Aeronautix May 09 '23 at 23:40
47

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.

Log in to your Google account, and use these links:

Step 1 [Link of Disabling 2-step verification]:

https://myaccount.google.com/security?utm_source=OGB&utm_medium=act#signin

Step 2: [Link for Allowing less secure apps]

https://myaccount.google.com/u/1/lesssecureapps?pli=1&pageId=none

It should be all good now.

Rahul Shenoy
  • 737
  • 6
  • 10
  • 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. – Ice Bear Dec 22 '20 at 07:06
44

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

gregStickle
  • 108
  • 5
Ephesus
  • 605
  • 5
  • 12
  • 2
    This is the most up to date answer, and the best one in my opinion. – vpz Apr 20 '23 at 11:19
  • 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. – Kevin G Jun 18 '23 at 20:13
  • @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. – Ephesus Jun 20 '23 at 08:48
  • I got it setup, I had the wrong variable set for my password. Thanks! – Kevin G Jun 23 '23 at 00:41
  • worked like a charm!! – GKV Jun 27 '23 at 03:04
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.

Gaurav
  • 479
  • 4
  • 5
14

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

OmG
  • 18,337
  • 10
  • 57
  • 90
  • 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. – Preben Andersen Jul 28 '22 at 18:58
  • @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. – OmG Jul 29 '22 at 16:35
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

Leo_Liu_MJ
  • 179
  • 1
  • 4
  • 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. – kevin_theinfinityfund Jun 10 '21 at 05:13
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

northcamel
  • 81
  • 1
  • 4
  • 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 database – random_hooman Oct 07 '21 at 05:23
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

vikash tiwary
  • 71
  • 1
  • 3
  • 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: ON – vikash tiwary Sep 27 '19 at 07:22
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

A. chahid
  • 184
  • 2
  • 5
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()
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
0
  1. Enable 2FA for your Google account
  2. Then set an app password for your app
  3. Use that new password
nathan liang
  • 1,000
  • 2
  • 11
  • 22
Ab_Fredo
  • 96
  • 6
  • 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. – Saad Abbasi Jul 03 '22 at 18:40
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.

Dat TT
  • 2,850
  • 2
  • 16
  • 18
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?)

Agrover112
  • 461
  • 5
  • 9
0

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

Wamz
  • 69
  • 5
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

luther wardle
  • 439
  • 5
  • 17
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.
fanbyprinciple
  • 554
  • 7
  • 14
-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('youremail@gmail.com', 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')
-2

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

Mining Pro
  • 25
  • 2