Hi guys I'm trying to read through an email inbox for my application - I'm using the zend framework here. The problem is that I'm unable to retrieve the message body for certain emails. The following is my code as to how I'm doing this:
$mail = new Zend_Mail_Storage_Imap($mail_options);
$all_messages = array();
$page = isset($_GET['page'])?$_GET['page']:1;
$limit = isset($_GET['limit'])?$_GET['limit']:20;
$offset = (($page-1)*$limit)+1;
$end = ($page*$limit)>$c?$c:($page*$limit);
for ($i=$offset;$i<=$end;$i++){
$h2t = new html2text();
$h2t->set_allowed_tags('<a>');
if(!$mail[$i])
break;
else{
$one_message = $mail->getMessage($i);
$one_message->id = $i;
$one_message->UID = $mail->getUniqueId($i);
$one_message->parts = array();
$one_message->body = '';
$count = 1;
foreach (new RecursiveIteratorIterator($mail->getMessage($i)) as $ii=>$part) {
try {
$tpart = $part;
//$tpart->_content = '';
$one_message->parts[$count] = $tpart;
$count++;
// check for html body
if (strtok($part->contentType, ';') == 'text/html') {
$b = $part->getContent();
if($part->contentTransferEncoding == 'quoted-printable')
$b = quoted_printable_decode($b);
$one_message->html_body = $b;
$h2t->set_html($b);
$one_message->body = $h2t->get_text();
}
//check for text body
if (strtok($part->contentType, ';') == 'text/plain') {
$b = $part->getContent();
if($part->contentTransferEncoding == 'quoted-printable')
$b = quoted_printable_decode($b);
$one_message->text_body = $b;
$one_message->body = $b;//$part->getContent();
}
} catch (Zend_Mail_Exception $e) {
// ignore
}
}
$all_messages[] = $one_message;
}
}
The problem is that randomly some messages don't return even a textbody or an html body. Even though if I check using a webvmail client those emails have a message body as well. WHat am I missing here?
You need to check if the mail is multipart message first, before looping over the parts. If it's not multipart, then the body will be exposed via
$mail->getContent()
instead of a part. Basic example: