molakalapalli ramesh molakalapalli ramesh - 1 year ago 327
Python Question

How to get unread messages and set message read flags over IMAP using Python?

import imaplib
def read():

userName = ""
password = "xxxx"
name = ''
email_ids = [userName]
data = []
imap_server = imaplib.IMAP4_SSL("",993)
imap_server.login(userName, password)'INBOX')
da = []
status, response = imap_server.status('INBOX', "(UNSEEN)")
unreadcount = int(response[0].split()[2].strip(').,]'))
print unreadcount

status, response =, '(FROM "")')
email_ids = [e_id for e_id in response[0].split()]
for e_id in email_ids:
_, response = imap_server.fetch(e_id, '(UID BODY[TEXT])')
print da


How to organise the code above, to read only unread mails?
Also, once we read them, how to mark the messages as read mail using Python?

Answer Source
import imaplib

def read(username, password, sender_of_interest):
    # Login to INBOX
    imap = imaplib.IMAP4_SSL("", 993)
    imap.login(username, password)'INBOX')

    # Use search(), not status()
    status, response =, 'INBOX', '(UNSEEN)')
    unread_msg_nums = response[0].split()

    # Print the count of all unread messages
    print len(unread_msg_nums)

    # Print all unread messages from a certain sender of interest
    status, response =, '(UNSEEN)', '(FROM "%s")' % (sender_of_interest))
    unread_msg_nums = response[0].split()
    da = []
    for e_id in unread_msg_nums:
        _, response = imap.fetch(e_id, '(UID BODY[TEXT])')
    print da

    # Mark them as seen
    for e_id in unread_msg_nums:, '+FLAGS', '\Seen')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download