-
-
Notifications
You must be signed in to change notification settings - Fork 84
Reading Messages
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_inboxget_starred_messagesget_important_messagesget_unread_messagesget_draftsget_sent_messagesget_trash_messagesget_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.
If you have any questions, comments, or suggestions, feel free to open an issue or submit a pull request with your changes.