0

I am reading the unread emails from my Inbox. I am getting the total number of unread emails, but I am unable to fetch the number of emails in a single email chain separately. For eg. There are three unread emails(One with a 10 email chain, one with a 4 email chain, and the last one with a 5 email chain). I am getting the output as 19 unread emails which I am correcting but storing the subjects in a pandas dataframe and then taking the unique values only, which gives me 3 unread emails. But I am still not unable to get the number of emails in a single email chain i.e 10, 4 and 5.

I am using the imaplib to get the emails.

mail = imaplib.IMAP4_SSL('imap.gmail.com')
(retcode, capabilities) = mail.login(username,password)
mail.select('Inbox')
n_unread_emails=0
(retcode, messages) = mail.search(None, '(UNSEEN)')
if retcode == 'OK':
   for num in messages[0].split() :
      n_unread_emails = n_unread_emails + 1
      typ, data = mail.fetch(num,'(RFC822)')
      for response_part in data:
         if isinstance(response_part, tuple):
             original = email.message_from_string(response_part[1])
             alerttrack = alerttrack.append({'Subject' : str(original['Subject']).replace('[Check_mk Alert RCA] ','')}, ignore_index = True)

n_unread_emails = alerttrack.Subject.nunique(dropna = True) 
print "Number of Unread Mails are " + str(n_unread_emails)

This is what I mean by a single email chain. The first chain has 4 emails, the second one has 1 , the third one has 1 and last one has 4 again. I want the output as 4,1,1,4.

Community
  • 1
  • 1
  • ***"fetch the number of emails in a single email chain separately"***: Do you mean attached emails? – stovfl Sep 16 '19 at 13:24
  • @stovfl Have attached the image for reference. – Yagyansh S. Kumar Sep 16 '19 at 13:39
  • Your image does not explain anything? As there is no such a thing called *email chain* i assume it's a attached email. Read [email-examples - Section:"example of how to unpack a MIME message"](https://docs.python.org/3/library/email.examples.html#email-examples) – stovfl Sep 16 '19 at 13:54
  • @stovfl - Okay I checked, and turns out email chain is same as an attached email. Let say you sent a mail to a person x, then you got a reply from that person and you guys had a long conversation over the email, of 20 email exchanges, this is what I am referring as an email chain. So when reading unread emails , these will be counted as 20 emails, but as a matter of fact this a just a single email. – Yagyansh S. Kumar Sep 17 '19 at 06:18
  • This is controlled with `Headers` like "`Message-ID, In-Reply-To:, References:`" or `X-Header`, read [what-do-x-headers-in-mails-stand-for](https://stackoverflow.com/questions/14469110/what-do-x-headers-in-mails-stand-for) – stovfl Sep 17 '19 at 06:51

0 Answers0