thatnicholascoder
thatnicholascoder

Reputation: 201

How can I send email from python with 2 Factor Authentication?

I have created python file that can send email using less secure apps turned on, but I need it off. How can I send email with 2FA?

# import simple mail transfer protocol library
import smtplib 

# import EmailMessage method
from email.message import EmailMessage

contacts = ['<[email protected]>', '<[email protected]>']
EMAIL_ADDRESS = '<my_gmail>'
EMAIL_PASSWORD = '<my_gmail_password>'

# Create empty Email Message object
msg = EmailMessage()
msg['Subject'] = 'Automated python email sender 5'
msg['From'] = EMAIL_ADDRESS
msg['To'] = contacts
msg.set_content('<sample_content>')

# contact manager we will make sure our connection is closed automatically without us doing it manually
# 465 is the port number for plain SMTP_SSL
# SMTP_SSL means you do not have to use ehlo() ans starttls()
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:

  smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
  smtp.send_message(msg)

What should I add to make 2FA work?

Upvotes: 6

Views: 14119

Answers (3)

Josue Gisber
Josue Gisber

Reputation: 366

Under security you have to generate a password for your application:

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('[email protected]', 'password generated by google')

server.sendmail('[email protected]', '[email protected]', 'Mail sent from program')
print('Mail Sent')

as you can see, you enter your email but instead of typing your own password you enter the password generated by google for your application

Upvotes: 1

nameless_hostage
nameless_hostage

Reputation: 1

Try setting up App Password for your Gmail. and used that app password for smtp login.

This will help Set Up APP-Password

Upvotes: 0

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 117016

I believe you would need to set up an App passwords let you sign in to your Google Account from apps on devices that don't support 2-Step Verification. Learn more

Its basically something thats setup in the users Google account.

Another thing to look at would be Display captcha

if that doesn't work you might need to look into Xoauth2

if you require 2fa

If you want to support 2fa then you should not be using the SMTP server and should be going though the Gmail API and using Oauth2 which will prompt a user to connect via their google account and google will control the 2fa themselves. SMTP servers are not designed to handel 2fa

Upvotes: 5

Related Questions