Reading Gmail Using PHP And IMAP
Introduction
Have you ever had the need to retrieve e-mail information and utilize the data for display on a website, GUI, or for some other web-based purpose? With PHP you can also parse emails in your inbox. You can easily turn email into a means of collecting data from your users and trigger different actions. For instance :
1) Create a support email account that parses all recieved emails and creates help tickets automatically
2) Create a text message distribution list. If there is ever a problem shoot an email to the specific account, upon receipt it texts that message to your team.
3) Update a blog or webpage. Capture all emails in an inbox and create blog posts or webpages out of them.
4) Setup an email parsing script that looks for keywords and sends back auto-generated responses.
Install composer dependency
For this tutorial, we will use ddeboer/imap library. Here’s how to install using composer:
You can follow the detail on how to use composer here.
Load the dependency
Once composer completed, you can load and start playing around:
Open a connection to Gmail
To open a connection, we will use Server class:
List all mailbox
List emails in a mailbox
To list emails in a mailbox, we execute getMessages() method of Mailbox instance:
Search emails in a mailbox
The library we’re using in this tutorial provide loads of ways to search emails.
We can search emails based on date:
• Before certain date
• On certain date
• After certain date
Search based on email address, like: bcc, from, to, or cc. Search criteria can also be combined with or. There’s also search criteria based on text data, like: search within body, subject, etc.
You can check more search criteria from the library’s repository.
Read email contents
The $mailbox->getMessages() will return arrays of Message. There are a lot of method you can use:
Updating emails
Within IMAP protocol, you can also update the email like moving to another inbox, set flag, and delete the email. Here is an example of what you can do:
For list of flags, you can consult the php documentation on imap library.
