PHP IMAP List all folders in the mailbox


Once you've connected to your mailbox, you'll want to take a look inside. The first useful command is imap_list. The first parameter is the resource you acquired from imap_open, the second is your mailbox string and the third is a fuzzy search string (* is used to match any pattern).

$folders = imap_list($mailbox, "{}", "*");
if ($folders === false) {
    echo "Failed to list folders in mailbox";
} else {

The output should look similar to this

    [0] => {}INBOX
    [1] => {}INBOX.Sent
    [2] => {}INBOX.Drafts
    [3] => {}INBOX.Junk
    [4] => {}INBOX.Trash

You can use the third parameter to filter these results like this:

$folders = imap_list($mailbox, "{}", "*.Sent");

And now the result only contains entries with .Sent in the name:

    [0] => {}INBOX.Sent

Note: Using * as a fuzzy search will return all matches recursively. If you use % it will return only matches in the current folder specified.