barbushin / php-imap

Manage mailboxes, filter/get/delete emails in PHP (supports IMAP/POP3/NNTP)
MIT License
1.65k stars 459 forks source link

[BUG] Truncated Attachment Names Resulting in Lost File Extensions #724

Open SirAlyon opened 1 month ago

SirAlyon commented 1 month ago

Environment PHP IMAP version: 5.0.1 PHP Version: 8.1.2-1ubuntu2.17 (cli) Type of execution: CLI

Describe the bug When processing emails with attachments through the PHP IMAP library, attachment names that are long and contain spaces are truncated. This results in filenames losing their extensions, which complicates file handling and can lead to potential data loss. This issue necessitates manual intervention to determine and append the correct file extensions.

To Reproduce Steps to reproduce the behavior:

Configure an IMAP connection using the Mailbox class. Fetch emails with attachments that have long names including spaces. Observe that the fetched attachment names are truncated and missing extensions.

The used code:

$mailsIds = $mailbox->searchMailbox('ALL');
foreach ($mailsIds as $mailId) {
    $mail = $mailbox->getMail($mailId);
    foreach ($mail->getAttachments() as $attachment) {
        // The following line is used to manually determine the extension due to the issue
        $extension = $this->determineExtension($attachment, pathinfo($attachment->name, PATHINFO_EXTENSION), $mail);
        echo $attachment->name . " extension: " . $extension;  // Output shows truncated names
    }
}

private function determineExtension($attachment, $fileInfo, $mail)
    {
        if (array_key_exists('extension', $fileInfo)) {
            return $fileInfo['extension'];
        } else {
            $attachmentExt = $this->extractExtensionFromMime($attachment, $mail);
            $attachment->name .= ".$attachmentExt";
            return $attachmentExt;
        }
    }

Expected behavior I expect that attachment names should be fully preserved, including spaces and their full length, without truncation. This would allow for accurate file handling and prevent the risk of data loss due to incorrect or missing file extensions.

Additional context This issue occurs only with certain emails that have attachments with particularly long names. The problem seems to be related to how the IMAP server or the PHP IMAP library handles or parses attachment headers.

Thank you for your attention to this matter. I appreciate any assistance you can provide in resolving this issue, and I am available for further details or to assist with testing solutions. :)