In this tutorial, you’ll learn how to send email using Gmail in Python. You’ll look at a couple of ways to send email using gmail. You’ll be making use of the smptlib Python module to send emails.

Using SMPTLIB To Send Email Using Gmail In Python

smptlib is a module provided by Python so you don’t need to install anything. Sending email using gmail in Python is a simple 4 step process :

  1. Import smtplib
  2. Create the SMTP server
  3. Login to the server
  4. Send email

Here is the Python code to send email :

import smtplib
server = smtplib.SMTP_SSL('smtp.gmail.com',465)
server.login(username,password)
server.sendmail(FROM_EMAIL_ADDRESS,TO_EMAIL_ADDRESS,MESSAGE)

The above code send email using SSL which uses port 465. In order to send email using TLS you need to specify a different port and start tls. Here is how the code to send email using TLS looks :

import smtplib
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(username,password)
server.sendmail(FROM_EMAIL_ADDRESS,TO_EMAIL_ADDRESS,MESSAGE)

You also need to allow access to less secure apps to gmail to be able to send email. For that go to google my account and check the allow less secure apps option.

Send Email Using Gmail In Python

Save the above changes and execute the Python script. You will be able to send email in Python using gmail.