Using Zend Framework To Iterate Through Your Gmail Mailbox

By admin

I was asked to research the most popular techniques to pull emails from a Gmail / Google Apps account. I figured that using Zend can be much easier than working with the built in imap_open function that comes with your PHP parser. Here are the steps to get it to work:

1. Download Zend Framework.

You have to choose the right version for your operating system. Then you have to choose if you want to Minimal Functionality Zend Framework or the Zend Framework Full Package. I chose the second one, since you never know what you may need in the future. If you do the same, you will be asked to register first on the Zend website and then download the framework.

Here is  the link: Zend Framework

2. Installation

You don’t really need to install anything. Just copy the library folder somewhere within your www server and add the right path to your php file. We are going to use the Mail functions:

<?
include(“Zend/Mail.php”);
include(“Zend/Mail/Storage/Imap.php”);
?>

You should change your path accordingly.

3. Add your php code

The only thing left is to add your code and play around with your email messages. Here is my code that you can use as an example:

<?
include(“Zend/Mail.php”);
include(“Zend/Mail/Storage/Imap.php”);
$mail = new Zend_Mail();
$mail = new Zend_Mail_Storage_Imap(array(‘host’ => ‘imap.gmail.com’,
‘port’ => ’993′,
‘user’ => ‘michael@xyz.com’,
‘password’ => ’12345′,
‘folder’ => ‘[Gmail]/All Mail’,
‘ssl’ => ‘SSL’));

$maxMessage = $mail->countMessages();
$time_generated1 = strtotime(date(“Y-m-d H:i:s”));

$n = 0;
$m = 0;
foreach ($mail as $messageNum => $message) {
if (isset($message->subject)) {
echo $n . ” ” .$message->subject . “<br>”;
$n++;
}
$m++;
if ($n == 10000) {
break;
}
}
echo “n: ” . $n . “<br>”;
echo “m: ” . $m . “<br>”;

$time_generated2 = strtotime(date(“Y-m-d H:i:s”));
$difference = $time_generated1 – $time_generated2;
echo(“Page generated in ” . $difference . ” seconds. “);
?>

You have to remember to check if the subject property exists. Apparently if the subject of the message is empty, it doesn’t exist and the framework throws the error:

Fatal error: Uncaught exception ‘Zend_Mail_Storage_Exception’ with message ‘cannot login, user or password wrong’ in C:\xampplite\htdocs\testing\Zend\Mail\Storage\Imap.php:279 Stack trace: #0 C:\xampplite\htdocs\testing\index.php(11): Zend_Mail_Storage_Imap->__construct(Array) #1 {main} thrown in C:\xampplite\htdocs\testing\Zend\Mail\Storage\Imap.php on line 279

However if you use the “if (isset($message->subject)) {” you should be good.

Share

Share your thoughts