How to remove/move messages using Zend Framework's Zend_Mail_Storage_Imap
Join the DZone community and get the full member experience.
Join For FreeI've been working on a nice feature for my local classified ad site which involved
retrieving emails (IMAP account) and analyzing the content.
What I wanted is when I am done with an email to move it in a folder so I don't have to reprocess it again.
Sounds easy and it should be that way.
For some reason when you delete OR move messages, their ID changes as
well. It could be a Zend Framework thing. So I had to collect the unique
IDs in the first loop then use a second loop to move the messages.
I decided to move the messages rather than deleting them because I am
using Google Mail for my domain and there is plenty of space.
If I ever need more space I can always order more.
Note: in my code below the messages are moved in '[Gmail]/All Mail' which of course is fine for Google hosted emails, you've got to change it depending on your IMAP setup.
Here is the code
try { $imap = new Zend_Mail_Storage_Imap ( array ( 'host' => 'imap.gmail.com:993', 'user' => 'your@gmail.com', 'password' => 'yourpwd', 'ssl' => true )); echo $imap->countMessages () . " messages found.\n"; $uniq_ids = array (); foreach ( $imap as $idx => $message ) { $messageUniqueId = $messageId = $imap->getUniqueId ( $idx ); $uniq_ids [] = $messageUniqueId; echo "[IDX: $idx UID: $messageUniqueId] Mail from '" . htmlentities ( $message->from, ENT_QUOTES, 'UTF-8' ) . "': to '" . htmlentities ( $message->to, ENT_QUOTES, 'UTF-8' ) . "': {$message->subject}\n<br/>"; echo '<pre>'; echo $message->getContent(); echo '</pre><br/>'; if ($idx && ($idx % 5 == 0)) { $imap->noop (); // keep alive } } // I will assume that the messages are processed so move 'em in All mail. I hope that's the archive. // Note your Folder may be differently. $cnt = 0; foreach ( $uniq_ids as $uniq_id ) { $cnt ++; if ($cnt % 5 == 0) { $imap->noop (); // keep alive } $messageId = $imap->getNumberByUniqueId ( $uniq_id ); $imap->moveMessage ( $messageId, '[Gmail]/All Mail' ); // this ID shifts all the time (--1) ?!? } } catch ( Exception $e ) { echo '' . $e; Zend_Debug::dump($e); }
Published at DZone with permission of Svetoslav Marinov, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments