Skip to content
Generic filters
Exact matches only

5 Python Tricks To Make Your Life More Productive | by Anupam Chugh | Aug, 2020

How many times were you forced to switch from the terminal to an internet browser just to view the recent emails? It happens a few times for everyone one of us.

You could accelerate your workflow and boost your productivity by getting rid of this context switch. Simply use the python imaplib module that lets you log into your email and fetch emails.

The library lets you filter emails by date, subject, sender, and more. So, with the following piece of code, you can fetch the latest n emails without manually logging into the browser:

Gist Link

RFC822 is an Internet Access Message protocol. You can also look up the Subject , Content and Date from every email response.

Note: For Gmail accounts with two-factor authentication, passing the password in the login method won’t work. You need to generate a token and set it in the password field by referring the below steps:

1. Log into your Gmail account.
2. Navigate to
3. In 'select app' choose 'Custom', give it any name name and press generate.
4. It will give you a token which you can paste in the above script.

Nowadays our inbox is full of promotional emails which only increase the inbox unread count. Selecting all messages and marking them as read is a time-consuming task when your inbox has more than 100 pages.

Luckily, the above imap module lets you search for UNSEEN messages and set them as read. First, change the search filter of the previous code to this:, '(UNSEEN)')

Finally, add the following piece of code in the for-loop:

original = email.message_from_bytes(response_part[1]),'+FLAGS','\Seen')

The backtick Seen is important. I managed to reduce the unread count of my inbox to zero with the above script!