Get emails from Gmail inbox with PHP

I was surfing and I found this interesting article about retrieve e-mails from a gmail account with php and imap.

Retrieve Your Gmail Emails Using PHP and IMAP

I tried to simplify this script putting it into a function with the parameters from and to because reading all my inbox it’s too lazy.

function loadGmailMails($from=0,$to=0){
	$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
	$username = 'dioli.luca@gmail.com';
	$password = '';
	
	$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
	$e = imap_search($inbox,'ALL');

	$emails = array();

	if($e) {
		rsort($e);//put the newest emails on top
		
		if($to == 0) $to = sizeof($e);
		
		for($i=$from;$i<$to;$i++){
			$overview = imap_fetch_overview($inbox,$e[$i],0);
			$message = imap_fetchbody($inbox,$e[$i],2);
			
			preg_match('/(?P<name>[a-zA-Z ]+)<(?P<address>.+)>/',$overview[0]->from,$match);
			trim($match['name']);
			
			$emails[] = array('read' => $overview[0]->seen, 'subject' => $overview[0]->subject, 'from' => array('name' => $match['name'], 'address' => $match['address']), 'date' => $overview[0]->date, 'message' => $message);
		}
	} 

	imap_close($inbox);
	
	return $emails;
}

Here you can find a demo.

Random posts