Forums

SMTP Email through Google

Needed SMTP to work for a class and 'localhost' does not work from PA servers. Here is what does work.

First, turn on 'Allow less secure apps' on Google => My Account => Sign-in & security (it is at the bottom of the page)

import smtplib
from email.mime.text import MIMEText

msg = MIMEText('This is my message')
msg['Subject'] = "Test Message"
msg['From'] = 'Your Name <yourname@gmail.com>'
msg['To'] = 'Your Name <yourname@gmail.com>'

server = smtplib.SMTP("smtp.gmail.com:587")
server.starttls()
server.login("yourname@gmail.com", "YourPW")
server.sendmail("yourname@gmail.com", "yourname@gmail.com", msg.as_string())

#And to close server connection
server.quit()

This link has more details. http://www.pythonforbeginners.com/google/sending-emails-using-google

Thanks for posting! I tend to recommend using an "app-specific password" -- you can find the option to generate one somewhere on that google security settings page. Specifically, if you're using two-factor auth, it's the only way to get SMTP to work...

Here's the link on the google page for setting up app-specific password: https://support.google.com/accounts/answer/185833?hl=en