Skip to content

Getting Started

Jeremy Ephron Barenholtz edited this page Sep 13, 2020 · 2 revisions

After downloading your Google API credentials and installing Simple Gmail (see Installation if you have not done that yet), create a new Gmail object to get started:

from simplegmail import Gmail

gmail = Gmail()

The first time you create a new Gmail object, it will open a browser window to ask you to log in and authenticate. This will save a file named "gmail-token.json" containing an authentication token. You can move "gmail-token.json" to a new location in order to bypass browser authentication. You will only need to authenticate through a browser again if the file is deleted; currently the token files contain a refresh token to automatically maintain validity after the token's stated expiry.

Now, you're all set to send, receive, and move around messages!

gmail.send_message(
    sender='margaret@gmail.com',
    to='god@aol.com',
    msg_plain="Are you there God? It's me, Margaret."
)

A few hours later...

msgs = gmail.get_unread_inbox(query='god@aol.com')
if msgs:
    # God responded!
    msgs[0].mark_as_important()

def print_email(message):
    print("To: " + message.recipient)
    print("From: " + message.sender)
    print("Subject: " + message.subject)
    print("Date: " + message.date)
    print("Preview: " + message.snippet)
    print("Body: " + message.plain)  # or message.html

print_email(msgs[0])

...and just like that, you've successfully sent, received, modified, and read your email in just a few lines of Python!

Clone this wiki locally