0

I would like to get the body of all unseen messages from an address using the IMAP library in Python 3. I was able to get all the message's body using this code here

import imaplib

mail = imaplib.IMAP4_SSL('imap.gmail.com')

mail.login( 'EMAIL', 'PASSWORD' )

mail.list

mail.select("inbox")


obj, data = mail.search(None, 'ALL')

for num in data [0].split():

    typ, data = mail.fetch(num, 'BODY[1]')

print('Message %s\n%s\n' % (num, data[0][1]))

mail.close()

Is there any way that I could narrow the search to just return unseen messages from a single address like email@address.com? This site here shows the unseen flag and this user was able to get a list of email addresses that I have received emails from using this script here. I was unable to figure out how to change the code to work because it was missing parts. Is there some way to combine these three to achieve the results I need?

Jack
  • 1,893
  • 1
  • 11
  • 28

1 Answers1

1

Replace ALL with UNSEEN. IMAP has many search keys you can use, ALL is not the only one.

Community
  • 1
  • 1
arnt
  • 8,949
  • 5
  • 24
  • 32
  • Thanks, I should have been able to catch that. Any way to filter per user? So then I just get unseen messages from one user not all? – Jack Jun 21 '19 at 12:52
  • Of course. You might have noticed the `FROM` key in that list? `search(None, 'UNSEEN FROM "arnt"')` will match unseen mail from me (and a few thousand other false positives, I'm not quite the only arnt). – arnt Jun 21 '19 at 12:55
  • Thanks that should do it. – Jack Jun 21 '19 at 13:22