How to get emails using PHP and IMAP ?
Reading emails from the Gmail account using PHP will be an enriching task for web developers for its simplicity of code through IMAP (Internet Message Access Protocol). Sometimes there can be a requirement in web projects or from a client that needs the complete management of inbox emails or access to email contents from his Gmail account. This feature can also be useful in email marketing or email newsletters that will be sent automatically on a particular schedule. So while researching Gmail account access, one should try listing emails from the Gmail account using PHP and its IMAP functions extension.
IMAP is an internet standard protocol used by clients to get emails from a mail server over a TCP/IP connection with SSL security. The IMAP extension available in PHP libraries provides efficient processing of its email structure and access to email messages via communicating with the email servers.
We use PHP code to connect to the Gmail server and use standard IMAP functions to open up the Gmail account and access or fetch emails based on certain criteria.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Basic requirements: The following are needed for the development of the functionality.
- PHP5 or latest PHP version.
- Enable the IMAP Extension in PHP installation.
- In Gmail account settings, IMAP should be enabled.
Steps to Enable IMAP in XAMPP:
- Go to php.ini configuration file
- Search for “;extension=php_imap.dll”
- Remove the beginning of semicolon and it should be “extension=php_imap.dll”
- Also edit max_execution_time = 4000
Steps to Enable IMAP in Gmail Account:
- Open Gmail.
- Click Settings.
- Select the Forwarding and POP/IMAP blue tab.
- Select “IMAP Access:” section and Enable IMAP radio button.
- Click Save Changes.
- Don’t forget to turn on access for less secure apps for Gmail account.
Note: For normal applications, an IMAP server listens on 143 port number.
PHP Code: The following is the HTML and PHP code to list emails from Gmail account. To connect to Gmail, the developer needs the individual’s “username” and “password” to be set in the code. Once connected, we search for all emails or emails based on certain criteria by using the imap_search() function. The emails are sorted in a reverse manner so that the latest mails are available on the top using the PHP rsort() function. This PHP function sorts an array in descending order. For every email returned, the subject, from, partial content, and date-time messages are captured. The imap_fetchbody() function fetches a particular section of the email body. So to get the plain text part of the email, we can use “1.1” option as the third parameter.
CSS code: The following is the code for the file “style.css” used in the above code.
Output: The following is the output shown for emails retrieved with subject “Comment”.