To see how many unread messages you have, you can call the list() method from the mailbox object. Use the following code to find out how many unread messages you have:
number_messages = len(mailbox.list()[1])
With this, we just have to loop and get the messages one by one to analyze them:
for i in range (num_messages):
print("Message number "+str(i+1))
print("--------------------")
# read message
response, headerLines, bytes = mailbox.retr(i+1)
The retr(i+1) method brings the message from the server whose number is indicated and marks it on the server as read. It is set to i+1 because the retr() method starts at 1 and not at zero. This method returns the server response, the message, and a few bytes related to the message that we are reading. The important thing is headerLines, which in some way contains all of the lines of the message.