user8802333
user8802333

Reputation: 489

Check if email is read or unread using imaplib and python?

I want to filter out emails based on who sent them to me and whether or not they have been read or unread, also I want to mark emails "read" after I analyze them.

I figured out how to filter by who sent them, how do I figure out the read/unread portion?

Thanks!

I am using this code (found online):

import imaplib
import email
from email.header import decode_header
import webbrowser
import os
import pprint
from imap_tools import MailBox, Q



username = input('Email: ')
password = input('Password: ')

# create an IMAP4 class with SSL 
imap = imaplib.IMAP4_SSL("imap.gmail.com")
# authenticate
imap.login(username, password)

status, messages = imap.select("INBOX", readonly=True)
# number of top emails to fetch
N = 15
# total number of emails
messages = int(messages[0])
            
for i in range(messages, messages-N, -1):
    # fetch the email message by ID
    res, msg = imap.fetch(str(i), "(RFC822)")
    for response in msg:
        if isinstance(response, tuple):
            # parse a bytes email into a message object
            msg = email.message_from_bytes(response[1])
            print(msg)
            # decode the email subject
            subject = decode_header(msg["Subject"])[0][0]
            if isinstance(subject, bytes):
                # if it's a bytes, decode to str
                subject = subject.decode()
            # email sender
            #print(msg.get("Seen"))
            from_ = msg.get("From")
            print("Subject:", subject)
            print("From:", from_)
            # if the email message is multipart
            if msg.is_multipart() and ("email of interest" in from_):
                # iterate over email parts
                for part in msg.walk():
                    # extract content type of email
                    content_type = part.get_content_type()
                    content_disposition = str(part.get("Content-Disposition"))
                    try:
                        # get the email body
                        body = part.get_payload(decode=True).decode()
                    except:
                        pass
                    if content_type == "text/plain" and "attachment" not in content_disposition:
                        # print text/plain emails and skip attachments
                        print(body)
                        
imap.close()
imap.logout()

Upvotes: 1

Views: 5600

Answers (1)

Vladimir
Vladimir

Reputation: 6726

I see that you have installed imap_tools lib, but you do not use it. So, you can reach your goal with it.

from imap_tools import MailBox, AND

# get unseen emails sent by [email protected] from INBOX folder
with MailBox('imap.mail.com').login('[email protected]', 'password', 'INBOX') as mailbox:
    # *mark emails as seen on fetch, see mark_seen arg
    for msg in mailbox.fetch(AND(from_='[email protected]', seen=False)):  
        print(msg.subject)
        for att in msg.attachments:
            print(att.filename)       
        body = msg.text or msg.html 
    

About "how do I figure out the read/unread", you can:

  1. request seen/unseen emails (mailbox.fetch criteria arg)
  2. use mailbox.fetch mark_seen arg for auto mark seen (*in example)
  3. use mailbox.flag method for explicitly set seen flag

https://github.com/ikvk/imap_tools

Upvotes: 3

Related Questions