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:
RFC822 is an Internet Access Message protocol. You can also look up the
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 https://security.google.com/settings/security/apppasswords
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:
Finally, add the following piece of code in the for-loop:
original = email.message_from_bytes(response_part)
Seen is important. I managed to reduce the unread count of my inbox to zero with the above script!