Friday, June 05, 2009

Gmail imap connect and seen/unseen

Some quick notes on imapping gmail (notice the novalidate-cert part... might save you some headaches), marking messages as read, and also about formatting PHP code for blogger. NOTE: code below has error checking removed for clarity.

$mbox = imap_open ("{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX", "your@gmail.com", "your");

$numMessages = imap_num_msg($mbox);
for ($jj = $numMessages; $jj > 0; $jj--) { //always have to go backwards, since message ID is dynamic
$header = imap_header ($mbox, $jj);
if ('U' == $header->Unseen) { //This message is unread
$body = '';
$struct = imap_fetchstructure($mbox, $jj);
if (!empty ($struct->parts)) {
$numParts = count ($struct->parts);
for ($kk = 0; $kk < $numParts; $kk++) {
$part = $struct->parts[$kk];
if ('PLAIN' == $part->subtype) {
$body = imap_fetchbody($mbox, $jj, $kk + 1);
}
}
} else {
$body = imap_body ($mbox, $jj);
}
imap_setflag_full($mbox, $jj, "\\Seen"); // mark as read
}
}
imap_close($mbox);
Formatting: I still don't have a good method of formatting for blogger. For this post, I used "Convert Special Characters into HTML Entities" by Stanley Shilov (Thanks!), switching to "Edit HTML" in Blogger, putting Stanley's optput between "pre" open and close tags, and then switching back to "compose" mode to clean up the output. There's GOT to be a better way... if anyone knows of any, please yell.