Reading Gmail With PHP IMAPHello my dear friends, Now this is quite interesting topic for all the PHP newbies and off course OLD bees..!! You might have seen many large PHP libraries that is designed to access emails and send emails. Well this one is going to be a lot more simpler than a HUGE MAIL Library.

To start with we should have the following minimum requirements

  • PHP5
  • IMAP enabled in your Gmail settings.
  • PHP IMAP Extension is enabled [Its a default package with PHP]

Lets start with connection configuration.

/* connect to gmail */
$hostname = ‘{imap.gmail.com:993/imap/ssl}INBOX’;
$username = ‘username@gmail.com’;
$password = ‘password’;

Replace the values with the Gmail account details that you need to access. The host name need not be altered, its the standard gmail IMAP address.

Now lets connect to Gmail using IMAP.

$inbox = imap_open($hostname,$username,$password) or die(‘Cannot connect to Gmail: ‘ . imap_last_error());

Once connected you can access the inbox using imap_search() function

$emails = imap_search($inbox,’UNSEEN’);

// ALL – All emails
// UNSEEN – Gets you the message which is not yet read.

imap_search returns all the email ID’s which are unread and we need to iterate through the ID’s to read the emails

if($emails) { // Check if there are any emails

rsort($emails); /* Sorts the email such that the new emails comes first*/

/*  Get the email one by one using ID */
foreach($emails as $email_number) {
// Get the email [headers]  like FROM, TO, SUBJECT, DATE, SERVER etc
$overview = imap_fetch_overview($inbox,$email_number,0);
echo $overview[0]->subject.”\n”;

// Get the Email Body
$message = imap_fetchbody($inbox,$email_number,1);

echo $message;  // Prints the message in Text format.
}

}

/* close the connection */
imap_close($inbox);

Download Source file

Hope you have enjoyed this Post.!! Leave your comments.

 

15 Responses to Reading Gmail With PHP IMAP

  1. Sophia says:

    It works. Thanks.

  2. Andy says:

    I have recently found a class on this site [link removed by moderator] , it’s working and seems promising

  3. MAX says:

    Dear Clain, I can’t even log:
    Warning: imap_open() [function.imap-open]: Couldn’t open stream {imap.gmail.com:993/imap/ssl}INBOX on line 10
    Cannot connect to Gmail:
    Can’t connect to gmail-imap.l.google.com,993:
    Connection timed out
    Windows Vista Pro, FireFox & Chrome
    Thank you for code Max

    • Clain Clain says:

      Hi Max,

      A firewall is preventing the local server in your system from accessing the Gmail server. You need to give permission for for the HTTP server to access the internet. Alternatively you can add exception to the port 993. This should fix the issue. You can try this code on an external production server and this should work well. There is no relation with the browsers and the PHP code, browsers just display the final outcome of a PHP code that runs on the server. Only HTML,CSS and JavaScript issues are related to browsers.

  4. shanyhi says:

    very nice article

  5. Priyanka says:

    I got error in console “500 Internal Server Error”

    • Clain Clain says:

      Hi Priyanka,

      I guess your server PHP configuration do not have PHP IMAP enabled. You can easily enable this by editing the php.ini file. Also you can install PHP IMAP Extension if its not installed by default. This will solve the internal server error.

  6. Igor says:

    I have some problems when try to receive the emails. When I run the script on server first i had receive error of type: to many login try or this one:
    The server encountered an internal error or misconfiguration and was unable to complete your request.

    Please help.

    • Clain Clain says:

      Igor,

      Did you made any modifications on the code? I guess you have the login option included in the code. Which is why you get “too many login” error.

      Can you copy paste you code here so that I can review your code and get it fixed

      • Igor says:

        Ok the problem is solved find the problem was with functio imap_search. I have one more question: If I send email let say with gmail, is possible after sending the email to append some new text inside the message which i have send?

        • Clain Clain says:

          An email send is send forever, you can never append any text at a later stage. It will be a security issue if this feature ever existed.

  7. Jeeva says:

    While trying this code i got the error like Couldn’t open stream {imap.gmail.com:993/imap/ssl}INBOX and Can’t connect to gmail-imap.l.google.com,993: Connection timed out. Please anybody help me to fix this.

    • Clain Clain says:

      You are not connected to the internet, or a firewall is preventing PHP [Apache] server from connecting to gmail server. Its a connectivity problem. Please check the firewall and connection settings.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>