How can the imap_fetchstructure() function be used to retrieve attachment names in PHP when accessing email mailboxes?

To retrieve attachment names from emails in PHP using the imap_fetchstructure() function, you can loop through each part of the email structure and check for attachments. The function will return an object representing the structure of the email, including any attachments. You can then extract the attachment names from this object.

// Connect to the IMAP server
$mailbox = imap_open('{mail.example.com:993/imap/ssl}INBOX', 'username', 'password');

// Get emails
$emails = imap_search($mailbox, 'ALL');

// Loop through each email
foreach ($emails as $email_number) {
    $structure = imap_fetchstructure($mailbox, $email_number);

    // Check for attachments
    if (isset($structure->parts) && count($structure->parts)) {
        foreach ($structure->parts as $part) {
            if (isset($part->disposition) && $part->disposition == "ATTACHMENT") {
                echo "Attachment name: " . $part->dparameters[0]->value . "<br>";
            }
        }
    }
}

// Close the connection
imap_close($mailbox);