Display mailbox folders with IMAP using PHP

David Carr

IMAP Tutorials PHP & MySQL

When using IMAP its likely you will want access to the users mailbox so they can view all their folders. This tutorial will explain how display mailbox folders using imap_list.

Before attempting to show the maiilbox folders a connection with the email server needs to be established with imap_open such as:

$mbox = imap_open("{mail.example.com:143/notls/norsh/novalidate-cert}", "sample@example.com","password");

For full details on using imap_open please look at this post <a href="http://www.dcblog.dev/tutorials/php/php-imap/connecting-to-an-imap-server-using-imap_open">Connecting to an imap server using imap_open</a>

To display mailbox folders use the function imap_list it requires 3 parameters first the imap_stream (connection) then the ref should normally be just the server specification as described in imap_open(). The third parameter dictates which folder to look in.

From the PHP manual:

There are two special characters you can pass as part of the pattern: '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

Some mail servers separate the mailboxes with } others use ] such as Gmail to remove these from the folder when viewing them a simply preg_match will do the job

//remove  any } characters from the folder
if (preg_match("/}/i", $list[0])) {
    $arr = explode('}', $list[0]);
}

Also to remove INBOX. from the mailbox name simply do a string replace

//remove INBOX. from the folder name
$folder = str_replace('INBOX.', '', stripslashes($arr[1]));

<p>The inbox is sometimes the last mailbox in the array so look through the array and if the first folder is not the inbox reverse the array</p>

//check if inbox is first folder if not reorder array
if($folder !== 'INBOX'){
    krsort($list);
}

Putting what we have so far the inbox will always come first, at this point nothing is displayed we're simple doing some prep work

$list = imap_list($mbox, '{mail.example.com:143/notls/norsh/novalidate-cert}', "*");

//remove  any } characters from the folder
if (preg_match("/}/i", $list[0])) {
    $arr = explode('}', $list[0]);
}

//also remove the ] if it exists, normally Gmail have them
if (preg_match("/]/i", $list[0])) {
    $arr = explode(']/', $list[0]);
}

//remove INBOX. from the folder name
$folder = str_replace('INBOX.', '', stripslashes($arr[1]));

//check if inbox is first folder if not reorder array
if($folder !== 'INBOX'){
    krsort($list);
}

Next loop through the array and display each mailbox I've commented each step, also to show the mailbox names correctly decode them with imap_utf7_decode.

<?php
//make sure the list is an array
if (is_array($list)) {

     //loop through rach array index
     foreach ($list as $val) {

        //remove  any } charactors from the folder
        if (preg_match("/}/i", $val)) {
            $arr = explode('}', $val);
        }

        //also remove the ] if it exists, normally Gmail have them
        if (preg_match("/]/i", $val)) {
            $arr = explode(']/', $val);
        }

        //remove any slashes
        $folder = trim(stripslashes($arr[1]));

        //remove inbox. from the folderName its not needed for displaying purposes
        $folderName = str_replace('INBOX.', '', $folder);


        echo "<p><a href="?folder=".imap_utf7_decode($folder)."">".ucwords(strtolower(imap_utf7_decode($folderName)))."</a></p>n";

    }

} else {
    echo "Folders not currently availablen";
}
?>
</pre>

<p>A lot of these steps are not essentially you could get all the mailbox folders and display them in a few lines as illustrated below but I believe taking the time to display the folders in a user friendly manor is much better.</p>

<pre lang="php">
<?php
$list = imap_list($mbox, "{imap.example.org}", "*");
if (is_array($list)) {
    foreach ($list as $val) {
        echo imap_utf7_decode($val) . "n";
    }
} else {
    echo "imap_list failed: " . imap_last_error() . "n";
}
?>

 

Copyright © 2006 - 2024 DC Blog - All rights reserved.