How to Access SMTP in Gmail with Python


In this article, we show how to access SMTP in gmail with Python.

SMTP stands for Simple Mail Transfer Protocol.

It is a protocol that allows a third-party service to gain access to emails on a certain email account, so that a user can send out emails through that email account.

Thus, SMTP allows a third-party service the ability to send mail to other people (granted there has been successful authentication of the account).

So, using a Python executer such as a IDLE, we can access SMTP in gmail and be able to send out email on a certain email account.

This is the power of SMTP. We can send out email via an email account through Python code, just as if we went to and logged into an email account using a username and password.

So, SMTP is a powerful concept.

You don't actually have to go to and log in in order to send email through that gmail account.

With powerful server-side languages such as Python, PHP, etc. we can access SMTP and authenticate into an account.

So let's see how this can be done in Python.

The code below gives us access to SMTP in gmail.

So, let's go over the code now shown above.

First, we must import the SMTP class from the smtplib module.

We first, we must specify the SMTP service that we want to connect to, in this case is gmail. So, the host name is "". If you're confused by this, see Gmail POP, IMAP, and SMTP Settings. This is reference chart that shows all of the settings of the various email protocols to use in Gmail.

The port to access SMTP using TLS (transport layer security) is port 587.

We then specify the username and password for the email account that we want to send outgoing email through. You can have to successfully authenticate into an email account to send email out.

We then have to specify which email address we are going to send from, which is the one we previously specified and which email address we are sending to, which can be one or many.

We then create the variable, CON, which connects us to the SMTP in gmail.

CON.starttls() starts the tls protol, which is the protocol by which email is sent in gmail. Gmail uses the tls (transport layer security) protocol for sending emails.

We then have to authenticate into the email account through which we want to send an email. We do this through the line, CON.login(username, password)

We then send an email through the sendmail() function. We send the simple message, "Hey"

We then exit out of the email account once we're finished sending the message.

So, this is how we can access SMTP in gmail with Python and send out messages.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...