Search code examples
pythonemailsmtplib

send email with Gmail Python


I am attempting to send an email, but I run into this error: smtplib.SMTPAuthenticationError: (534, b'5.7.9 Application-specific password required. Learn more at\n5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor d2sm13023190qkl.98 - gsmtp')

In the web URL i dont see anything super useful, would anyone have any tips? For SO purposes I left the email account passwords as test versus sharing my person info..

import smtplib
import ssl


# User configuration
sender_email = 'test@gmail.com'
receiver_email = 'test@gmail.com'
password = 'test'



# Email text
email_body = '''
    This is a test email sent by Python. Isn't that cool?
'''

# Creating a SMTP session | use 587 with TLS, 465 SSL and 25
server = smtplib.SMTP('smtp.gmail.com', 587)
# Encrypts the email
context = ssl.create_default_context()
server.starttls(context=context)
# We log in into our Google account
server.login(sender_email, password)
# Sending email from sender, to receiver with the email body
server.sendmail(sender_email, receiver_email, email_body)
print('Email sent!')

print('Closing the server...')
server.quit()

Solution

  • You must allow the "Less secure apps" in Google configurations.

    Here is the link of another thread about it : Link