title: Check if email is read or unread using imaplib and python?
body: <p>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 &quot;read&quot; after I analyze them.</p>
  <p>I figured out how to filter by who sent them, how do I figure out the read/unread portion?</p>
  <p>Thanks!</p>
  <p>I am using this code (found online):</p>
  <pre><code>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(&quot;imap.gmail.com&quot;)
  # authenticate
  imap.login(username, password)
  
  status, messages = imap.select(&quot;INBOX&quot;, 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), &quot;(RFC822)&quot;)
      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[&quot;Subject&quot;])[0][0]
              if isinstance(subject, bytes):
                  # if it's a bytes, decode to str
                  subject = subject.decode()
              # email sender
              #print(msg.get(&quot;Seen&quot;))
              from_ = msg.get(&quot;From&quot;)
              print(&quot;Subject:&quot;, subject)
              print(&quot;From:&quot;, from_)
              # if the email message is multipart
              if msg.is_multipart() and (&quot;email of interest&quot; 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(&quot;Content-Disposition&quot;))
                      try:
                          # get the email body
                          body = part.get_payload(decode=True).decode()
                      except:
                          pass
                      if content_type == &quot;text/plain&quot; and &quot;attachment&quot; not in content_disposition:
                          # print text/plain emails and skip attachments
                          print(body)
                          
  imap.close()
  imap.logout()
  </code></pre>