Move emails to selected IMAP Folder

David Carr

2 min read - 13th Feb, 2012

Moving email from one IMAP mailbox folder another is a simple process this short tutorial will show you how.

First create a form with a list the list will be populated with all the mailbox folders using imap_list. Remember you'll need an open connection to the server first in this example my stream is referenced in $mbox.

<form action="" method="post">
$list = imap_list($mbox, '{}', "*");
echo "<select name='moveMail'>n";
echo "<option value=''>Move selected emailsn";
if (is_array($list)) {
     foreach ($list as $val) {

     if (preg_match("/}/i", $val)) {
     $arr = explode('}', $val);

     if (preg_match("/]/i", $val)) {
    $arr = explode(']/', $val);

    $box = trim(stripslashes($arr[1]));
    $box = $arr[1];
    $boxval = str_replace('INBOX.', '', $box);
    echo "<option value=".imap_utf7_decode($box).">".imap_utf7_decode($boxval)."</option>n";

echo "</select>n";
<input type="submit" name="submit" value="Move to Folder" />

The following code will run as long as a folder has been selected and the form has been submitted. If no folder has been selected nothing will happen.

The selected email is passed to a variable called $mailbox which is passed to a function called imap_mail_move which will copy the email to the desired folder it also request the imap stream and the message number. Since the function copies the email we need to remove it from the current folder, this is easily done by calling imap_expunge which will remove any emails waiting to be deleted.

//move mail to mailbox
    if($_POST['moveMail'] !=''){
        $mailbox = $_POST['moveMail'];
        //move mail to new folder
        //delete selected email from current folder


Add a comment

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