Wednesday, January 11, 2012

Read Gmail Inbox using IMAP


There are two input fields in the below form. they are available to capture your gmail username(fully email) and password. Once you provide your username and password, just click login button tosend request to the imapEmail.php file.

loginForm.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
</head>
<body>

<form method="post" name="login_form" id="login_form" action="imapEmail.php">


    Email <input type="text" name="email" id="email"/> <br/>
    Password <input type="password" name="password" id="password"/>

    <input type="submit" name="login" id="login" value="login" />

</form>

</body>
</html>



The below file will receive the Gmail username (email)  and password send by the loginForm.html page. then it will make necessary connection with the Gmail server to make the IMAP functionality work.

imapEmail.php
<?php

/*
Author:Chathuranga Tennakoon
Email: chathuranga.t@gmail.com
Web : http://chathurangat.blogspot.com
*/

/*check whether the request is POST*/
if(isset($_POST)){

    /* connect to gmail */
    $hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
    /* getting the username */
    $username = $_POST['email'];
    /*getting the password */
    $password = $_POST['password'];

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

    /* grab emails */
    $emails = imap_search($inbox,'ALL');

    /* if emails are returned, cycle through each... */
    if($emails) {

        /* begin output var */
        $output = '';

        /* put the newest emails on top */
        rsort($emails);

        /* for every email... */
        foreach($emails as $email_number) {

            /* get information specific to this email */
            $overview = imap_fetch_overview($inbox,$email_number,0);
            $message = imap_fetchbody($inbox,$email_number,2);

            /* output the email header information */
            $output.= '<div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">';
            $output.= '<span class="subject">'.$overview[0]->subject.'</span> ';
            $output.= '<span class="from">'.$overview[0]->from.'</span>';
            $output.= '<span class="date">on '.$overview[0]->date.'</span>';
            $output.= '</div>';

            /* output the email body */
            $output.= '<div class="body">'.$message.'</div>';
        }

        echo $output;
    }

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

}//if post request comes

?>



hepe this will helpful for you !

regards
Chathuranga Tennakoon
chathuranga.t@gmail.com