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.
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.
php5enmod imap
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
<?php set_time_limit(4000); $imapPath = '{imap.gmail.com:993/imap/ssl/novalidate-cert/norsh}Inbox'; $username = 'yourmail@gmail.com'; $password = 'xyzxyz'; $inbox = imap_open($imapPath,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error()); $emails = imap_search($inbox,'UNSEEN'); $mail_content = ''; $i=0; 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); $i++; } echo '<pre>'; print_r($mail_content); // colse the connection imap_expunge($inbox); imap_close($inbox); ?>
imap_search: This function returns an array of messages matching the given search criteria. It performs
IMAP Functio ns
imap_searcimap_search($inbox,'ALL'); Return all the mails.
imap_body R
imap_setflag_full Sets flag
Have a Question? Share your query by writing in comment below.
- A. P. J. Abdul Kalam
Related Topics
- Convert P
dataHP SON API urlto J - Gene
ate RSS Feed for websir ng php and json scriptte usi - Ajax add,view and
ete using mysqlidel - Active and inactive users concept using php and Ajax
- How to Make
Sima le Seap r ine usch Eng PHP and MySQLiing - PDO basic insert,view,update,d
te with phpele function - Send e
tml template using phpmail with h - Login with facebook using codeigniter
No comments:
Post a Comment