Speed up development with full-stack environments for every branch.

Learn More

Retrieve messages from Gmail by subject [Python and IMAP]

2180 Runs 11227 Views 4513 Copies

Uses python's imaplib library to connect to Gmail via SSL and retrieve emails that match a subject. Change the 3rd parameter on line 11 to change the subject line to search for.

Saved

Saved

sundip 66

sundip
published 3 years ago

import getpass, imaplib

M = imaplib.IMAP4_SSL("imap.gmail.com", 993)
email = raw_input("Email address: ")
password = getpass.getpass()
M.login(email, password)

M.select()
typ, data = M.search(None, 'SUBJECT', "Gmail")
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    print('Message %s\n%s\n' % (num, data[0][1]))
M.close()
M.logout()
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).