How to send emails with gmail using python

Now that you have your SMTP connection set up and authorized your app with Google, you can finally use Python to send email with Gmail.

Using the email string we constructed above, and the connected/authenticated server object, you need to call the .sendmail() method. Here is the full code, including the methods for closing the connection:


import smtplib
gmail_user = '[email protected]'  
gmail_password = 'iodocs987'

sent_from = gmail_user  
to = ['[email protected]', '[email protected]']  
subject = 'OMG Super Important Message'  
body = "Hey, what's up?\n\n- You"

email_text = """\  
From: %s  
To: %s  
Subject: %s

%s
""" % (sent_from, ", ".join(to), subject, body)

try:  
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(gmail_user, gmail_password)
    server.sendmail(sent_from, to, email_text)
    server.close()

    print ('Email sent!')
except:  
    print ('Something went wrong...')

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

allowgmailpython

Once that is set (see my screenshot below), it should work.

mailsendbypython

Rate this post