Fun with Python and Gmail

In this article, I will show you how to log in to a Gmail account via IMAP and search your inbox for a mail.

Why you ask? Well, for me it was needed for one of my automation tasks for FamilyPoint application we are working on. When an ivitation is sent, we needed an automatic way of getting the invite code and register an account with that code...

Another usecase could be: notify me when I receive an email from X or when I receive an email with a certain string in the subject or body. I'll let you decide why you need it or how you will use it :)

Anyhow, the script below will log in to your gmail account, perform a search, and return email body.

import imaplib, json
username = "MyUsername"
password = "MyPa$$word"
search = "(TO <a href=""></a>)" # Search for all emails that are sent to <a href=""></a>
m = imaplib.IMAP4_SSL('')
m.login(username, password)"[Gmail]/All Mail")
response = list()
typ, data =, search)
for num in data[0].split():
    typ, data = m.fetch(num, '(UID BODY[TEXT] BODY[HEADER.FIELDS (SUBJECT)])')
    response.append(dict(subject=data[1][1].split(': ')[1], body=data[0][1]))
return json.dumps(response)

Hope you'll find some good use for this!