What could be causing the issue with imap_fetchstructure not retrieving attachments as expected in PHP?

The issue with imap_fetchstructure not retrieving attachments as expected in PHP could be due to incorrect handling of multipart messages or incorrect parsing of the structure. To solve this issue, you can iterate through the parts of the message structure recursively to retrieve the attachments.

function fetchAttachments($structure, $messageNumber, $imapStream) {
    $attachments = array();

    if(isset($structure->parts) && count($structure->parts)) {
        foreach($structure->parts as $partNumber => $part) {
            $attachments = array_merge($attachments, fetchAttachments($part, $messageNumber, $imapStream));
        }
    }

    if(isset($structure->disposition) && $structure->disposition == "ATTACHMENT") {
        $attachments[] = array(
            'attachment' => imap_fetchbody($imapStream, $messageNumber, $partNumber),
            'filename' => $structure->dparameters[0]->value
        );
    }

    return $attachments;
}

// Usage
$attachments = fetchAttachments($structure, $messageNumber, $imapStream);