Problem with displaying and downloading email attachments using the zend framework

Posted by Ali on Stack Overflow See other posts from Stack Overflow or by Ali
Published on 2010-04-04T06:51:32Z Indexed on 2010/04/04 6:53 UTC
Read the original article Hit count: 471

Hi guys I'm trying to display emails in my inbox and their respective attachments. At the same time I also wish to be able to download the attachments however I'm kinda stuck here. Here is the code I use to display the attachments:

$one_message = $mail->getMessage($i);
$one_message->id = $i;
$one_message->UID = $mail->getUniqueId($i);

// get the contact of this message
$email = array_pop(extract_emails_from($one_message->from));

$one_message->contactFrom = $contact_manager->get_person_from_email($email);
$one_message->parts = array();
foreach (new RecursiveIteratorIterator($mail->getMessage($i)) as $ii=>$part) {

try {
    $tpart = $part;
    $one_message->parts[$ii] =  $tpart; // put the part of the message indexed with what I assume is its position

    if (strtok($part->contentType, ';') == 'text/html') {

        $b = $part->getContent();

        $h2t->set_html($b);
        $one_message->body = $h2t->get_text();

    }

    if (strtok($part->contentType, ';') == 'text/plain') {
        $b = $part->getContent();

        $one_message->body = $part->getContent();
    }
} catch (Zend_Mail_Exception $e) {
    // ignore
}
}

And I display the attachments using the following link:

?action=download&element=email-attachment&box=inbox&uid=<?php echo $one_message->UID;?>&id=<?php echo $one_message->id;?>&part=<?php echo $ii;?>

The part variable is the index taken from the loop above

However when I try to download using the exact same code as above modified slightly:

$id = $_GET['id'];
$pid = $_GET['part'];
$one_message = $mail->getMessage($id);

foreach (new RecursiveIteratorIterator($mail->getMessage($id)) as $ii=>$part) {

if($pid == $ii):
 $content = base64_decode($part->getContent());
 $cnt_typ = explode(";" , $part->contentType);
 $name = explode("=",$cnt_typ[1]);

 $filename = $name[1];//It is the file name of the attachement in browser
 //This for avoiding " from the file name when sent from yahoomail
 $filename = str_replace('"'," ",$filename);
 $filename = trim($filename);

 header("Cache-Control: public");
 header("Content-Type: ".$cn_typ[1]);

 header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
 header("Content-Transfer-Encoding: binary");

 echo $content;

 exit;
endif;
}

For some reason it doesn't work at all. I did a var dump and noticed that in the for loop with the reverseiterator teh indexes $ii returned are 1 - 2 - 2 !! Whats going on here how can the indexes be repeated? How can I tell one part from the others?

© Stack Overflow or respective owner

Related posts about zend-framework

Related posts about email-attachments