Skip to content

Reading Messages

Jeremy Ephron Barenholtz edited this page Sep 14, 2020 · 1 revision

The Gmail object provides several convenience functions for retrieving your messages which all rely on the same underlying general get_messages() function. The full list of these convenience functions is:

  • get_unread_inbox
  • get_starred_messages
  • get_important_messages
  • get_unread_messages
  • get_drafts
  • get_sent_messages
  • get_trash_messages
  • get_spam_messages

For the purposes of this section, we will only use the get_unread_inbox function.

As always, we need to set up our Gmail object. Assume this has taken place for all future code snippets.

from simplegmail import Gmail

gmail = Gmail()

To start, let's retrieve our unread inbox messages:

msgs = gmail.get_unread_inbox()

This returns a list of Message objects, which contain attributes like sender, recipient, date, subject, snippet (Gmail's preview line of the email), and the message body in two fields, plain and html. plain is the plaintext message, while html contains the HTML message, typically what you see in your Gmail client. plain is practically better for printing and parsing in a program, though neither field is guaranteed to exist, and you can send an email without either.

When an email is sent from the online Gmail client, it will contain both a plain and html message body, as Gmail constructs the message with both, and this is typically true for major email clients, but the plaintext message can often be missing in emails from mass email campaign services.

You may want to print out your messages like the following:

def print_email(message):
    print("To: " + message.recipient)
    print("From: " + message.sender)
    print("Subject: " + message.subject)
    print("Date: " + message.date)
    print("Preview: " + message.snippet)
    
    # For safety, check that plain and html are not None before printing
    if message.plain:
        print("Body: " + message.plain)
    elif message.html:
        print("Body: " + message.html)
    else:
        print("No message body.")

for msg in msgs:
    print_email(msg)

Note that recipient and sender are given in Gmail's format, which, if the address has a listed name, is of the format "John Doe <johndoe@gmail.com>". I may add built-in parsing in the future.

Clone this wiki locally