Tutorials, PHP & MySQL, IMAP

Move emails to selected IMAP Folder

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">
<?php
$list = imap_list($mbox, '{imap.example.org}', "*");
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" />
</form>

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.

<?php
//move mail to mailbox
if(isset($_POST['moveMail']))
{
    if($_POST['moveMail'] !=''){
        $mailbox = $_POST['moveMail'];
        //move mail to new folder
        @imap_mail_move($mbox,$msgno,$mailbox);
        //delete selected email from current folder
        @imap_expunge($mbox);
    }
}
?>

 

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.