Read Gmail Using Python: A Step-by-Step Guide

Scripting is where Python really pays off. The Python Scripting Essentials Bundle has the kind of small automation projects you would build for work.

Gmail still speaks POP3 and IMAP, so you can read your mail from Python with the poplib module in the standard library. No extra package needed.

You need to turn on two things in your Gmail account first, otherwise the login is refused.

Gmail and Python provide a seamless integration that allows users to access and read their emails programmatically. The poplib module in Python facilitates the interaction with Gmail servers to fetch emails.

POP or Post Office Protocol is the medium of communication between your computer and the Gmail server. It’s crucial to understand that POP is designed to retrieve mail and not send it.

To start the process, ensure you enable POP support in your Gmail settings to facilitate the reading process via Python.

Accessing Gmail with Python

The following code outlines the steps to connect and authenticate your Gmail account using Python:

 
import poplib
import string, random
import StringIO, rfc822
import logging

SERVER = "pop.gmail.com"
USER = "XXXXXX"
PASSWORD = "XXXXXX"

# Establish connection to Gmail server
logging.debug('connecting to ' + SERVER)
server = poplib.POP3_SSL(SERVER)

# Authenticate with server
logging.debug('authenticating')
server.user(USER)
server.pass_(PASSWORD)

Fetching and Reading an Email

After successfully connecting and authenticating with the Gmail server, you can retrieve and read your emails. Here’s how you can achieve this:

 
import poplib
import string, random
import StringIO, rfc822
import logging

SERVER = "pop.gmail.com"
USER = "XXXXXXXXXXX"
PASSWORD = "XXXXXXXXXXX"

# Establish connection to Gmail server
logging.debug('connecting to ' + SERVER)
server = poplib.POP3_SSL(SERVER)

# Authenticate with server
logging.debug('authenticating')
server.user(USER)
server.pass_(PASSWORD)

# Fetch list of emails
logging.debug('fetching email list')
resp, items, octets = server.list()

# Retrieve the first email from the list
id, size = string.split(items[0])
resp, text, octets = server.retr(id)

# Convert email text to Message object
text = string.join(text, "\n")
file = StringIO.StringIO(text)
message = rfc822.Message(file)

# Display email details
print(message['From']),
print(message['Subject']),
print(message['Date']),
# Uncomment to display email content
#print(message.fp.read())

This code establishes a connection, authenticates, fetches a list of emails, retrieves the first email from that list, and then displays pertinent details about the email. The full content of the email can be displayed by uncommenting the appropriate line.

Looking for more examples? Download more network examples here.

Setting up Gmail

  • Turn on 2-Step Verification in your Google account.
  • Open myaccount.google.com/apppasswords and create an app password for mail.
  • Use that 16 character password in the script, not your Google password. Your normal password will not work here.

The code itself:

  • poplib.POP3_SSL('pop.gmail.com', 995) opens the connection over SSL.
  • server.user(email) and server.passwd(app_password) log in.
  • server.stat() gives you the number of messages.
  • server.retr(i) downloads message number i.
  • Split the raw text on a blank line, the part after it is the body.
  • server.quit() closes the connection.

The newest messages are at the end of the list, so loop backwards if you want the recent ones first. Use the IMAP module instead if you also want to move or delete mail while you are in there.

If you want to try this yourself, the exercises on PyChallenge turn the same idea into a few short problems with instant feedback.