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?
conn = imaplib.IMAP4_SSL(imap_server)
conn.login(imap_user, imap_password)
status, messages = conn.select('INBOX')
if status != "OK":
print "Incorrect mail box"
exit()
print messages
Something like this will do the trick.
There’s also a duplicate question here – Find new messages added to an imap mailbox since I last checked with python imaplib2?
Two useful functions for you to retrieve the body and attachments of the new message you detected (reference: How to fetch an email body using imaplib in python?) –
PS: If you pass by in 2020 after python 2.7 death: replace
email.message_from_string(data[0][1])withemail.message_from_bytes(data[0][1])