Reading an email inbox with PHP – IMAP.

This is a short tutorial on how to connect to an IMAP email inbox using PHP’s imap functions. To keep things simple, I will connect to the inbox and then retrieve any emails that were received in the last week.

Let’s take a look at the following example:

A drill-down of the PHP code above:

  1. We opened an IMAP stream to our inbox. Note that you will have to change the connection details to match your own inbox. It is worth pointing out that 143 is the default port for IMAP and that notls disables any TLS encryption.
  2. If the imap_open function returns a boolean FALSE value, then it means that we were unable to connect to the inbox in question. In the code above, I throw an Exception with the error message that is returned by imap_last_error.
  3. We then created our search criteria. In this example, I told the imap_search function to return emails that have been received in the last week (7 days ago). If you want to retrieve all emails that are currently in the inbox, then you will need to set the $search variable to ALL. If you only want to view unread emails, then you can set the $search variable to UNSEEN. It is important to note that the imap_search function will return a boolean FALSE value if no emails were found. i.e. It will not return an empty array.
  4. Finally, we loop through the emails that were returned before printing out the subject and sender’s email address. Note that we use FT_PEEK with the imap_fetchbody function because we want to read the email without flagging it as read! You can remove this parameter if you want your PHP script to mark unseen emails as being read.