Search code examples
phpimap

How to move a mail message to a folder with php imap


I can't seem to move my mail messages to my saved folder. Here is my code:

$mbox = imap_open("{".$mail_server.":".$mail_port."}".$mail_folder,            
$mail_username, $mail_password) or die("Error opening mailbox: ".imap_last_error());

$countnum = imap_num_msg($mbox);
$msglist = array();

if( $countnum > 0 ) {
$num = 1;


while ($num <= $countnum) {

$msglist[] = $num;
$num++;

     }//end while loop

}

//move the email to our saved folder
imap_mail_move($mbox,implode(',',$msglist),'INBOX/Saved');
imap_expunge($mbox);
imap_close($mbox);

When I run this script nothing happens. The message stays in the inbox. Any thoughts? Thanks!


Solution

  • From looking at the docs for imap-mail-move() I see you've glued your range together with , and your counting up from 1 so theres no need for the for loop:

    <?php 
    $mbox = imap_open("{".$mail_server.":".$mail_port."}INBOX", $mail_username, $mail_password) or die("Error opening mailbox: ".imap_last_error());
    
    $countnum = imap_num_msg($mbox);
    
    if($countnum > 0) {
        //move the email to our saved folder
        $imapresult=imap_mail_move($mbox,'1:'.$countnum,'INBOX/Saved');
        if($imapresult==false){die(imap_last_error());}
        imap_close($mbox,CL_EXPUNGE);
    }
    ?>