Open In App

How to get emails using PHP and IMAP ?

Last Updated : 15 Oct, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Basic requirements: The following are needed for the development of the functionality.

  1. PHP5 or latest PHP version.
  2. Enable the IMAP Extension in PHP installation.
  3. In Gmail account settings, IMAP should be enabled.

Steps to Enable IMAP in XAMPP:

  1. Go to php.ini configuration file
  2. Search for “;extension=php_imap.dll”
  3. Remove the beginning of semicolon and it should be “extension=php_imap.dll”
  4. Also edit max_execution_time = 4000

Steps to Enable IMAP in Gmail Account:

  1. Open Gmail.
  2. Click Settings.
  3. Select the Forwarding and POP/IMAP blue tab.
  4. Select “IMAP Access:” section and Enable IMAP radio button.
  5. Click Save Changes.
  6. 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. 
 

HTML




<!DOCTYPE html>
<html>
  
<head>
    <link rel="stylesheet" href=
    <link rel="stylesheet" href="style.css">
  
    <script>
        function getEmails() {
            document.getElementById('dataDivID')
                .style.display = "block";
        }
    </script>
</head>
  
<body>
    <h2>List Emails from Gmail using PHP and IMAP</h2>
  
    <div id="btnContainer">
        <button class="btn active" onclick="getEmails()">
            <i class="fa fa-bars"></i>Click to get gmail mails
        </button>
    </div>
    <br>
      
    <div id="dataDivID" class="form-container" style="display:none;">
        <?php
            /* gmail connection,with port number 993 */
            $host = '{imap.gmail.com:993/imap/ssl/
                    novalidate-cert/norsh}INBOX';
            /* Your gmail credentials */
            $user = 'YOUR-EMAIL@GMAIL.COM';
            $password = 'YOUR-PASSWORD';
  
            /* Establish a IMAP connection */
            $conn = imap_open($host, $user, $password) 
                 or die('unable to connect Gmail: ' . imap_last_error());
  
            /* Search emails from gmail inbox*/
            $mails = imap_search($conn, 'SUBJECT "Comment"');
  
            /* loop through each email id mails are available. */
            if ($mails) {
  
                /* Mail output variable starts*/
                $mailOutput = '';
                $mailOutput.= '<table><tr><th>Subject </th><th> From  </th
                           <th> Date Time </th> <th> Content </th></tr>';
  
                /* rsort is used to display the latest emails on top */
                rsort($mails);
  
                /* For each email */
                foreach ($mails as $email_number) {
  
                    /* Retrieve specific email information*/
                    $headers = imap_fetch_overview($conn, $email_number, 0);
  
                    /*  Returns a particular section of the body*/
                    $message = imap_fetchbody($conn, $email_number, '1');
                    $subMessage = substr($message, 0, 150);
                    $finalMessage = trim(quoted_printable_decode($subMessage));
  
                    $mailOutput.= '<div class="row">';
  
                    /* Gmail MAILS header information */                   
                    $mailOutput.= '<td><span class="columnClass">' .
                                $headers[0]->subject . '</span></td> ';
                    $mailOutput.= '<td><span class="columnClass">' . 
                                $headers[0]->from . '</span></td>';
                    $mailOutput.= '<td><span class="columnClass">' .
                                 $headers[0]->date . '</span></td>';
                    $mailOutput.= '</div>';
  
                    /* Mail body is returned */
                    $mailOutput.= '<td><span class="column">' . 
                    $finalMessage . '</span></td></tr></div>';
                }// End foreach
                $mailOutput.= '</table>';
                echo $mailOutput;
            }//endif 
  
            /* imap connection is closed */
            imap_close($conn);
            ?>
    </div>
</body>
  
</html>


CSS code: The following is the code for the file “style.css” used in the above code.

CSS




body {
   font-family: Arial;
 }
  table {
     font-family: arial, sans-serif;
     border-collapse: collapse;
     width: 100%;
 }
  tr:nth-child(even) {
     background-color: #dddddd;
 }
 td, th {
     padding: 8px;
     width:100px;
     border: 1px solid #dddddd;
     text-align: left;                
 }
 .form-container {
     padding: 20px;
     background: #F0F0F0;
     border: #e0dfdf 1px solid;                
     border-radius: 2px;
 }
 * {
     box-sizing: border-box;
 }
 
 .columnClass {
     float: left;
     padding: 10px;
 }
 
 .row:after {
     content: "";
     display: table;
     clear: both;
 }
 
 .btn {
     background: #333;
     border: #1d1d1d 1px solid;
     color: #f0f0f0;
     font-size: 0.9em;
     width: 200px;
     border-radius: 2px;
     background-color: #f1f1f1;
     cursor: pointer;
 }
 
 .btn:hover {
     background-color: #ddd;
 }
 
 .btn.active {
     background-color: #666;
     color: white;
 }


Output: The following is the output shown for emails retrieved with subject “Comment”.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads