Sending email with python. Google disables less secure apps

Viewed 2715

I am trying to send email using python. My code was working fine before Google disabled 'less secure apps'. My email address and password are both correct.

server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
serverEmail = "EMAILADDRESS"
serverPw = "QWERTY"
server.login(serverEmail, serverPw)
subject = "Rejection"
body = "Hi! You've been unfortunately declined access to our system."
message = f'Subject: {subject}\n\n{body}'
server.sendmail("EMAILADDRESS", doctorEmail['email'], message)
server.quit()

I get this error now:

smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted.

I get this error when i use server.starttls():

smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server.

3 Answers

This is working for me. You need to generate an app password for this. See https://support.google.com/accounts/answer/185833?hl=en

import smtplib as smtp

connection = smtp.SMTP_SSL('smtp.gmail.com', 465)
    
email_addr = 'my_email@gmail.com'
email_passwd = 'app_password_generated_in_Google_Account_Settings'
connection.login(email_addr, email_passwd)
connection.sendmail(from_addr=email_addr, to_addrs='recipient@something.com', msg="Sent from my IDE. Hehe")
connection.close()

For some reason, all of my emails are ending up in SPAM folder of the recipient account though.

2-step verification turn on then head over to App password

enter image description here

After is generated passwords

import smtplib 
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as connection:  
    email_address = 'your_email_sender@gmail.com'
    email_password = 'App_Passwords_is_generated'
    connection.login(email_address, email_password )
    connection.sendmail(from_addr=email_address, to_addrs='receiver_email@something.com', 
    msg="subject:hi \n\n this is my message")

Google disabled access for 'less secure apps' for a time on June 2, but around 7 PM US Eastern Time they re-enabled it. So if you just waited a few hours, you didn't have to do anything.

I suspect that somehow they got smacked with the 'law of unintended consequences' but it won't surprise me if they turn this access off again at some point.

Related