Having reached the conclusion of my series on getting Google Analytics data by email I had an enquiry from someone asking how to find only the unread email messages using PHP IMAP. This is simple enough to do and can be done either when looping through the messages or using the imap_search function.
IMAP vs POP
Please note that the Unseen flag will only work if you are connecting to an IMAP mailbox and not when connecting using POP. POP servers have no concept of read and unread messages.
Looping through the messages
I’ve covered how to loop through messages using PHP IMAP in an earlier post so be sure to read that for more information.
To find the unread emails when looping through look for the ->Unseen property like so:
$count = imap_num_msg($connection); for($msgno = 1; $msgno <= $count; $msgno++) { $headers = imap_headerinfo($connection, $msgno); if($headers->Unseen == 'U') { ... do something ... } }
You could use this to look for specific emails or show in a list view which emails have not yet been read.
Using imap_search
I’ve covered how to use the imap_search function in my looping through messages to find a specific subject post so be sure to read that for more information.
There’s a flag called UNSEEN which you can use to search for the unread emails. You would call the imap_search function with the UNSEEN flag like so:
$result = imap_search($connection, 'UNSEEN');
If you need to combine this with more search flags, for example searching for messages from me@example.com, you could do this:
$result = imap_search($connection, 'UNSEEN FROM "me@example.com"');
For a complete list of the available flags, refer to the criteria section of the imap_search manual page on the PHP website (www.php.net/imap_search)