imap-fetchbody() will decode attached email messages inline with the rest of the email parts, however the way it works when handling attached email messages is inconsistent with the main email message.
With an email message that only has a text body and does not have any mime attachments, imap-fetchbody() will return the following for each requested part number:
(empty) - Entire message
0 - Message header
1 - Body text
With an email message that is a multi-part message in MIME format, and contains the message text in plain text and HTML, and has a file.ext attachment, imap-fetchbody() will return something like the following for each requested part number:
(empty) - Entire message
0 - Message header
1 - MULTIPART/ALTERNATIVE
1.1 - TEXT/PLAIN
1.2 - TEXT/HTML
2 - file.ext
Now if you attach the above email to an email with the message text in plain text and HTML, imap_fetchbody() will use this type of part number system:
(empty) - Entire message
0 - Message header
1 - MULTIPART/ALTERNATIVE
1.1 - TEXT/PLAIN
1.2 - TEXT/HTML
2 - MESSAGE/RFC822 (entire attached message)
2.0 - Attached message header
2.1 - TEXT/PLAIN
2.2 - TEXT/HTML
2.3 - file.ext
Note that the file.ext is on the same level now as the plain text and HTML, and that there is no way to access the MULTIPART/ALTERNATIVE in the attached message.
Here is a modified version of some of the code from previous posts that will build an easily accessible array that includes accessible attached message parts and the message body if there aren't multipart mimes. The $structure variable is the output of the imap_fetchstructure() function. The returned $part_array has the field 'part_number' which contains the part number to be fed directly into the imap_fetchbody() function.
<?php
function create_part_array($structure, $prefix="") {
if (sizeof($structure->parts) > 0) { foreach ($structure->parts as $count => $part) {
add_part_to_array($part, $prefix.($count+1), $part_array);
}
}else{ $part_array[] = array('part_number' => $prefix.'1', 'part_object' => $obj);
}
return $part_array;
}
function add_part_to_array($obj, $partno, & $part_array) {
$part_array[] = array('part_number' => $partno, 'part_object' => $obj);
if ($obj->type == 2) { if (sizeof($obj->parts) > 0) { foreach ($obj->parts as $count => $part) {
if (sizeof($part->parts) > 0) {
foreach ($part->parts as $count2 => $part2) {
add_part_to_array($part2, $partno.".".($count2+1), $part_array);
}
}else{ $part_array[] = array('part_number' => $partno.'.'.($count+1), 'part_object' => $obj);
}
}
}else{ $part_array[] = array('part_number' => $prefix.'.1', 'part_object' => $obj);
}
}else{ if (sizeof($obj->parts) > 0) {
foreach ($obj->parts as $count => $p) {
add_part_to_array($p, $partno.".".($count+1), $part_array);
}
}
}
}
?>