This is a smaller portion of a bigger project. I need to only get unread emails and a parse their headers. How can I modify the following script to only get unread emails?>
The above answer does not actually work anymore or maybe never did but i modified it so it returns only unseen messages, it used to give : error cannot parse fetch command or something like that here is a working code :
mail = imaplib.IMAP4_SSL('imap.gmail.com')
(retcode, capabilities) = mail.login('email','pass')
mail.list()
mail.select('inbox')
n=0
(retcode, messages) = mail.search(None, '(UNSEEN)')
if retcode == 'OK':
for num in messages[0].split() :
print 'Processing '
n=n+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])
print original['From']
print original['Subject']
typ, data = mail.store(num,'+FLAGS','\\Seen')
print n
I think the error was coming from the messages[0].split(' ') but the above code should work fine.
Also, note the +FLAGS instead of -FLAGS which flags the message as read.
EDIT 2020: If you pass by in 2020 after python 2.7 death: replace email.message_from_string(data[0][1]) with email.message_from_bytes(data[0][1])