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="mailto:my_email+123@gmail.com">my_email+123@gmail.com</a>)" # Search for all emails that are sent to <a href="mailto:my_email+123@gmail.com">my_email+123@gmail.com</a>
 
m = imaplib.IMAP4_SSL('imap.gmail.com')
m.login(username, password)
m.select("[Gmail]/All Mail")
 
response = list()
 
typ, data = m.search(None, 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!

Comments