Mail management

array imap_sort ( resource imap_stream, int criteria, int reverse [, int options [, string search_criteria]])

bool imap_delete ( resource imap_stream, int msg_number [, int options])

bool imap_undelete ( resource imap_stream, int msg_number)

bool imap_expunge ( resource imap_stream)

bool imap_mailboxmsginfo ( resource imap_stream)

string imap_last_error ( void )

To bring to a close this brief of chapters on email, I want to look at the topic of mail management over IMAP - how to sort messages, how to delete messages, and such.

Rather than just looping from 0 to imap_num_msg() as have been doing to date, you can have the mail server sort its data and return an array of message numbers sorted as requested. This is all done using the imap_sort() function, which takes three parameters: an IMAP stream, a sort type, and whether to reverse the list of not.

The second parameter must be one and only one of the following:


...sorts by


Sent date of message


Date message arrived in your inbox


"From" address


Message subject


"To" address


"CC" address


Size of message

So, for example, this script prints out a list of all the messages received, reverse sorted by the name of the sender (so Zeev comes before Zak):

    $imap = imap_open("{}INBOX", "username", "password");
    $messages = imap_sort($imap, SORTFROM, 1);

    foreach ($messages as $message) {
        $header = imap_header($imap, $message);
        $prettydate = date("jS F Y", $header->udate);
        print "{$header->fromaddress} - $prettydate\n";


Moving on, imap_delete() and imap_undelete() serve to allow you to delete and undelete messages from an IMAP email box. Yes, that might sound obvious, but there is more to it than there first appears because IMAP messages are marked for deletion as opposed to deleted. Both of these two functions take an IMAP stream and a message number to alter as their only two parameters, and both act immediately. However, what they do is toggle the D flag of the selected message that looked at it in 16.6.2 - when you call imap_delete(), the message still exists, but its deleted flag ("D") is switched on. This message still shows up in the inbox and can still be read like any other message, but it is marked for deletion. When imap_undelete() is called, the D flag is simply removed.

So, how do you actually delete messages? Well, there is another function entirely for that purpose: imap_expunge(). This takes an IMAP stream as its only parameter, and permanently deletes all messages that have their deleted flag set. If you really want to get smart, you can pass a second parameter to IMAP close after the IMAP stream - if you set this to CL_EXPUNGE, imap_close() automatically calls imap_expunge() before closing the connection, essentially deleting all marked messages before shutdown.

With all that in mind, this next example will delete messages 1, 3, and 5 from a mailbox:

    $imap = imap_open("{}INBOX", "username", "password");
    imap_delete($imap, 1);
    imap_delete($imap, 2);
    imap_delete($imap, 3);
    imap_delete($imap, 4);
    imap_delete($imap, 5);

    imap_undelete($imap, 2);
    imap_undelete($imap, 4);


Note that messages 1 to 5 are all marked for deletion, then 2 and 4 are unmarked with imap_undelete(). Finally, imap_expunge() is called to delete the marked messages, and the connection is closed.

Author's Note: When messages have been expunged, they are removed from the mail box and all subsequent messages are shifted forward by one. If you are accessing messages by their sequence, be aware that these sequence numbers will changed if you expunge messages, so only expunge when you are finished!

The second to last function I would like to demonstrate is imap_mailboxmsginfo(), which returns information on the IMAP connection passed in as its only parameter. The return value is an object with a selection of properties set for you:


Current date on server


Number of deleted messages


Type of server


Name of the mail box


Number of messages in total


Number of recent messages


Total size of message box in bytes


Number of unread messages

For example, if you just want to know the size of a mailbox, you could use this code:

    $imap = imap_open("{}INBOX", "username", "password");
    $check = imap_mailboxmsginfo($imap);
    $size = number_format($check->Size / 1024, 2);
    echo "Your mailbox is {$size}kb.\n";

Author's Note: As this function has to count the size of all messages in the inbox, it may take some time to execute.

The last, but not least, IMAP function we are going to look at is imap_last_error(). This is the easiest IMAP function out there, as it takes no parameters at all and returns a string containing information on the last error encountered in the current script. You should, of course, always put error checking in your code, and using imap_last_error() is the easiest way to print out meaningful error messages.

    $imap = imap_open("{}INBOX", "username", "password");

    if (!$imap) {
        print imap_last_error();
    } else {
        // IMAP code here



Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Transferring files over FTP >>

Previous chapter: Dealing with MIME-encoded messages

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.