How to fetch unread emails from a mailbox

| By Webner

Python code to fetch Unread emails from a Mailbox

Script to check and fetch the unread inbox using the following packages.
1. imaplib
2. email
3. csv

IMAP is an email retrieval protocol which does not download the emails. It just reads them and displays them. This is very useful in low bandwidth condition. Python’s client-side library called imaplib is used for accessing emails over imap protocol. IMAP stands for Internet Mail Access Protocol.

Step 1: Make your email less secure.

Step 2: Script to fetch the emails

#!/usr/bin/env python
    small script to check for unread count on imap inbox
import imaplib
import email
import csv

count = ''
    mail = imaplib.IMAP4_SSL('')	
    mail.login('Your email address', 'Password') # connect to inbox.
    return_code, data =, 'UnSeen')
    #count = len(mail_ids[0].split(" "))
    mail_ids = data[0].decode()
    id_list = mail_ids.split()
    first_email_id = int(id_list[0])
    latest_email_id = int(id_list[-1])
    with open('persons.csv', 'w', newline="") as csvfile:
        filewriter = csv.writer(csvfile, delimiter=',',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
        filewriter.writerow(['From', 'Subject'])
        for i in range(latest_email_id,first_email_id, -1):
            typ, data = mail.fetch(str(i),'(RFC822)')
            for response_part in data:
                    if isinstance(response_part, tuple):
                        msg = email.message_from_string(response_part[1].decode("utf-8"))
                        email_subject = msg['subject']
                        email_from = msg['from']
                        filewriter.writerow([email_from, email_subject])
except Exception as e: print(e)

print (count)

Step 3: Run your python file with command (python3 and it creates a “persons.csv” file in your working directory.

Leave a Reply

Your email address will not be published. Required fields are marked *