0

I want to read the unread mails only but what i have done so far it showing already read mails too please help me find out a way to do it

This is what i have done so far

import imaplib
import email
from bs4 import BeautifulSoup
import webbrowser

m = imaplib.IMAP4_SSL("imap.gmail.com", 993)
m.login("mymail@gmail.com","pass")
m.select('"[Gmail]/All Mail"')

result, data = m.uid('search', None, 'HEADER Subject "Website Amazon Adfice"') # search all email and return uids
if result == 'OK':
    for num in data[0].split():
        result, data = m.uid('fetch', num, '(RFC822)')
        if result == 'OK':
            email_message = email.message_from_bytes(data[0][1])    # raw email text including headers
            print('From:' + email_message['From'])
            print('Subject:'+ email_message['Subject'])
            #print('Body:'+ email_message['Body'])
            if email_message.is_multipart():
                for payload in email_message.get_payload():
                    # if payload.is_multipart(): ...
                    print (payload.get_payload())
                    soup = BeautifulSoup(payload.get_payload(), 'html.parser')
                    link_text = ""

                    for a in soup.find_all('a', href=True, text=True):
                        link_text = a['href']
                        webbrowser.open(link_text)

            else:
                print (email_message.get_payload())

m.close()
m.logout()

its reading all the mails including already read mails

Any help would be highly appreciated

Swarnadeep
  • 325
  • 1
  • 3
  • 17
  • `m.select('"[Gmail]/Unread"')` ? – andreis11 Apr 09 '20 at 18:32
  • Showing error " File "C:\Users\SDP\Desktop\online learning\stack mail.py", line 12, in result, data = m.uid('search', None, 'HEADER Subject "cams_db"') # search all email and return uids File "C:\Users\SDP\AppData\Local\Programs\Python\Python38-32\lib\imaplib.py", line 876, in uid raise self.error("command %s illegal in state %s, " imaplib.IMAP4.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED" – Swarnadeep Apr 10 '20 at 04:59
  • not working bro showing error – Swarnadeep Apr 10 '20 at 07:03
  • my bad; I beiieve this might do the trick [link](https://stackoverflow.com/questions/13210737/get-only-new-emails-imaplib-and-python) – andreis11 Apr 10 '20 at 13:39

0 Answers0