12

How to Download Gmail Emails in a Given Label

Posted (Updated ) in PHP

EDIT Aug 6 2011: If you’re having trouble connecting to
{imap.gmail.com:993/imap/ssl}
try
{imap.gmail.com:993/imap/ssl/novalidate-cert/norsh}
If you get a ‘Too many incorrect logins’ error, you can unlock your account again here.

I’m a big fan of the Android platform and have been using an application called SMS Backup to send all SMS’s to Gmail for archiving (now replaced by SMS Backup+). To cut a long story short, I needed to download those SMS’s with a PHP script. SMS Backup had uploaded them all under the creatively named SMS label and so I needed a way to download all emails with a specified label. It turned out to be a relatively thing to do once you know what you’re looking for.

A quick Google search (I’m such a fanboy) will lead you to this page where a script is provided to download all email from Gmail using the IMAP protocol:

<?php
/* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'your username here';
$password = 'your password here';
 
/* 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);

This gets us half way there. Now – to filter by label. As it turns out, this is ridiculously simple. Change the $hostname variable to this:

$hostname = '{imap.gmail.com:993/imap/ssl}SMS';

And with that, ladies and gentlemen, we have a completed script!

…but what if you want to retrieve only your Spam mail (not that you would), your starred mail or your deleted mail? This is also quite possible. After much more Googling I came across this blog post detailing what you need to put in your $hostname. In the instance above, it’d be

$hostname = '{imap.gmail.com:993/imap/ssl}[Gmail]/Trash';