Skip to content

Memory for fetched message attachments is never released which results in memory leak #531

Open
@robkleinee

Description

@robkleinee

A long-running script which fetches and processes messages with attachments from a mailbox with this IMAP package results eventually in a 'memory size of ... bytes exhausted'.

I think this has something to do with the fetched attachments. It seems that these attachments somehow are never released from memory?

A workaround is to set manually the attachments to an empty collection after the attachments are processed.

Code to duplicate the bug (be sure to have emails with attachments in the mailbox)

Package version: 5.5.0
PHP: 8.1.x

$inboxFolder = $client->getFolder('inbox');

while (true) {
    echo 'Memory usage: ' . memory_get_usage() . PHP_EOL;

    $messages = $inboxFolder
        ->messages()
        ->all()
        ->limit(1)
        ->get();

    // Process the messages
}

Workaround (Extended on 2025-05-08)

$inboxFolder = $client->getFolder('inbox');

while (true) {
    echo 'Memory usage: ' . memory_get_usage() . PHP_EOL;

    $messages = $inboxFolder
        ->messages()
        ->all()
        ->limit(1)   // The workaround only works when only one message is retrieved and processed at at time
        ->get();

    $messages->each(
        function ($message) {
            // TODO: Process the message

            // Optionally move the message to another folder/mailbox
            $movedMessage = $message->move('name_of_mailbox');

            // Workaround to fix memory issue, for both message and the moved message
            $movedMessage->setAttachments(AttachmentCollection::make([]));
            $message->setAttachments(AttachmentCollection::make([]));
        }
    );
}

Am I doing something wrong? Or is there a memory leak?

Thanks in advance!

PS: It seems like this package is abandoned?

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingenhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions