Read Your Gmails Using PHP and IMAP - Mostlikers

28 January, 2016

Read Your Gmails Using PHP and IMAP

In this post we will be seeing, how to access gmail inbox via PHP code? We will be using PHP 5 IMAP  function to retrieve the gmail emails. IMAP function is used to open streams to POP3 and NNTP servers.

Retrive Gmails using php and IMAP

Live Demo               Download

Before we proceed, let us see the IMAP settings in the Gmail and the local server.
  • PHP 5 should be supported.
  • IMAP should be enabled in Gmail account.
  • IMAP extension should be enabled in your server.
In case your Xmapp and Lampp do not support IMAP function follow the below steps to install IMAP in windows and Ubuntu.

Enabling IMAP in Windows

IMAP is not enabled by default in Xampp distribution, In the file "\xampp\php\php.ini" search for ";extension=php_imap.dll" and remove the beginning semicolon from the line, it enables IMAP, The changed line looks like extension=php_imap.dll

Enabling IMAP in Linux

Execute the below commands in your the Linux terminal.

apt-get install php5-imap
php5enmod imap
service apache2 restart

The first line is PHP5 IMAP module, the second line is to enable the IMAP and the last is to restart the apache server.

Now we got to know how to enable the IMAP, now let us dig into the actual scenario to read the Gmail inbox.

PHP Code

    $imapPath = '{}Inbox';
    $username = '';
    $password = 'xyzxyz';   
    $inbox = imap_open($imapPath,$username,$password) or 
    die('Cannot connect to Gmail: ' . imap_last_error());
    $emails = imap_search($inbox,'UNSEEN');
    $mail_content = ''; 
    foreach($emails as $mail) {
      $headerInfo = imap_headerinfo($inbox,$mail);      
      $mail_content .= $headerInfo->subject.'<br/>';
      $mail_content .= $headerInfo->toaddress.'<br/>';
      $mail_content .= $headerInfo->date.'<br/>';
      $mail_content .= $headerInfo->fromaddress.'<br/>';
      $mail_content .= $headerInfo->reply_toaddress.'<br/>';
      $emailStructure = imap_fetchstructure($inbox,$mail);      
      if(isset($emailStructure->parts)) {
         $mail_content .= imap_body($inbox, $mail, FT_PEEK); 
      $status = imap_setflag_full($inbox,$mail, "\\Seen \\Flagged", ST_UID);
    echo '<pre>'; print_r($mail_content); 
    // colse the connection

imap_search: This function returns an array of messages matching the given search criteria. It performs a search on the mailbox currently opened in the given IMAP stream.

IMAP Functions

imap_search It will get unseen email list in your mail box.
imap_search($inbox,'ALL'); Return all the mails.
imap_body Read the mail message body.
imap_setflag_full Sets flags on a parti

Have a Question? Share your query by writing in comment below.

"If you want to shine like a sun, first burn like a sun."
                                         - A. P. J. Abdul Kalam

Related Topics

No comments:

Post a Comment