Retrieve Your Gmail Emails Using PHP and IMAP
In this post, I will show you, how you can write a program that fetches the recent emails from your gmail inbox. In this post I will be just fetching 4 latest emails.
<?php
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$server = '{imap.googlemail.com:993/imap/ssl/novalidate-cert}INBOX';
$username = 'email@gmail.com';
$password = 'password';
// try to connect
$inbox = imap_open($server,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
$no=imap_num_msg($inbox); //get total number of mails
$newsArray=array();
//get the latest 4 emails
for($i=$no;$i>$no-4;$i--){
$news=array();
$news['text']=imap_fetchbody($inbox,$i,1);
$overview = imap_fetch_overview($inbox,$i);
$news['author']=$overview[0]->from;
$news['status']=$overview[0]->seen;
$news['date']=$overview[0]->date;
$news['title']=$overview[0]->subject;
array_push($newsArray,$news);
}
foreach($newsArray as $n){
echo "Author: ".$n['author']."<br />";
echo "Title: ".$n['title']."<br />";
echo "Date: ".$n['date']."<br />";
echo "Text: ".$n['text']."<br />";
echo "<hr />";
}
/* close the connection */
imap_close($inbox);
?>
Hope you like it. :)
Thankyou!
ReplyDelete