title: Using imaplib in python reading a POSTGRES SQL column to check whether the email id is present in mail box or not
body: <p>I have a mailbox  where I have selected a particular folder using IMAP, and I have a PostgreSQL database in which a column is present with list of email ids' values. My ultimate objective is to search for the list of email ids present in the database with that of the mail box.</p>
  <p>My aim is to get the values from the column of the database and to give it in imap.uid and search the email id one by one , if present I will be performing a delete action on the mail box, if not present then I will be passing it</p>
  <pre class="lang-py prettyprint-override"><code>import re
  import imaplib
  import email
  import traceback
  import psycopg2
  from psycopg2 import Error
  
  try:
      # Mail box Log in
      imap = imaplib.IMAP4_SSL(&quot;imap.mail.yahoo.com&quot;)
      imap.login(&quot;****&quot;, &quot;****&quot;)
      print(&quot;Connection to Email-Box established successfully&quot;)
      # Data Base connection
      connection = psycopg2.connect(user=&quot;postgres&quot;,
                                    password=&quot;*****!!&quot;,
                                    host=&quot;localhost&quot;,
                                    port=&quot;****&quot;,
                                    database=&quot;postgres&quot;)
  
      # Create a cursor to perform database operations
      connection.autocommit = True
      cursor = connection.cursor()
      print(&quot;Connection to Data Base established successfully&quot;)
      imap.select(&quot;Temp&quot;)
  
      query = 'SELECT email_id from &quot;Python&quot;.&quot;test_table&quot; '
      cursor.execute(query)
      mail_id = cursor.fetchall()
      result, data = imap.uid('search', None, 'ALL')
      # iterate through messages
      for num in data[0].split():
          typ, data = imap.uid('fetch', num, '(BODY[HEADER.FIELDS (From)])')
          # parse data to get message id
          if data in mail_id:
              print(&quot;value exists&quot;)
          else:
              print(&quot;Nil&quot;)
  except Exception as e:
      traceback.print_exc()
      print(str(e))
  </code></pre>