Search code examples
phpphp-imap

Unable to get inbox from gmail using php imap


Hello guys am trying to use php imap to get email message but am getting Network is unreachable error

this is my code

<h1>Gmail Email Inbox using PHP with IMAP</h1>
<?php
    if (! function_exists('imap_open')) {
        echo "IMAP is not configured.";
        exit();
    } else {
        ?>
<div id="listData" class="list-form-container">
    <?php
        
        /* Connecting Gmail server with IMAP */
        $connection = imap_open('{imap.gmail.com:993/imap/ssl}INBOX', 'My correct email address here', 'My correct password here') or die('Cannot connect to Gmail: ' . imap_last_error());
        
        /* Search Emails having the specified keyword in the email subject */
        $emailData = imap_search($connection, 'SUBJECT "Article "');
        
        if (! empty($emailData)) {
            ?>
    <table>
        <?php
            foreach ($emailData as $emailIdent) {
                
                $overview = imap_fetch_overview($connection, $emailIdent, 0);
                $message = imap_fetchbody($connection, $emailIdent, '1.1');
                $messageExcerpt = substr($message, 0, 150);
                $partialMessage = trim(quoted_printable_decode($messageExcerpt)); 
                $date = date("d F, Y", strtotime($overview[0]->date));
                ?>
        <tr>
            <td><span class="column">
                    <?php echo $overview[0]->from; ?>
            </span></td>
            <td class="content-div"><span class="column">
                    <?php echo $overview[0]->subject; ?> - <?php echo $partialMessage; ?>
            </span><span class="date">
                    <?php echo $date; ?>
            </span></td>
        </tr>
        <?php
            } // End foreach
            ?>
    </table>
    <?php
        } // end if
        
        imap_close($connection);
    }
    ?>
</div>

Am supposed to get emails from my gmail account and display them in the html as seen in the code above. Please guys let's show some love.


Solution

  • Well the problem is not from my code but originally when saying unreachable, It was based on a closed port 993. And on getting the certificate error and Authentication failure invalid authentication. That's on Gmail's end. I don't know if turning on less secured app will resolve the issue cos I can't find it either. I mean Gmail don't support authenticating with plain text as email and password. They use OAUTH and if you which to connect to Gmail you mucst use it else Gmail won't connect. I found out after so many attempts. Hope this helps other frustrated users. If you need to get gmail connected use OAuth which works fine in my case.