How to fetch unread emails from a mailbox

Author - Maniraj Singh
26.07.2019
|
0 Comments
||

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 = ''
try:
    mail = imaplib.IMAP4_SSL('imap.gmail.com')	
    mail.login('Your email address', 'Password')
    mail.select() # connect to inbox.
    return_code, data = mail.search(None, '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 getEmailCount.py) and it creates a “persons.csv” file in your working directory.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

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