Home » Php » php – How would I move a message from Gmail Inbox to a label?

php – How would I move a message from Gmail Inbox to a label?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m trying to move messages away from Inbox into Processed label with this code:

$inbox = imap_open($host,$user,$pass) or die('Error: ' . imap_last_error());

if( $emails = imap_search($inbox,'ALL') )
{
    foreach($emails as $email_number) {
        imap_mail_move($inbox, $email_number, 'Processed') or die('Error');
    }

}
imap_expunge($inbox);
imap_close($inbox);

Unfortunately, while the messages get the Processed label, they’re still left in Inbox too.

How would I make them go away from Inbox?

How to&Answers:

Actually… The reason why the emails were left in the inbox was that when imap_mail_move did it’s thing, the IDs of all the leftover messages got decremented by one, so when the foreach loop moved to the next message, one message was left behind. This skipping a message repeated for every iteration. That’s why it seemed that imap_mail_move was not working.

The solution is to use unique message UIDs instead of potentially repeating IDs:

$inbox  = imap_open( $host, $user, $pass );
$emails = imap_search( $inbox, 'ALL', SE_UID );

if( $emails ) {
    foreach( $emails as $email_uid ) {
        imap_mail_move($inbox, $email_uid, 'processed', CP_UID);
    }
}

Answer:

You have to move the message to the “[Gmail]/All Mail” folder, after you “move it” to a tag folder which is not really a folder as Gmail see’s it, just letting Gmail know to add that tag.

So through IMAP:

1) When a message is moved to “[Gmail]/TAG” folder it tells Gmail to add the “TAG” to the message, but does not do any sort of moving of the message.

2) When a message is moved to “[Gmail]/All Mail” folder it tells Gmail to remove it from the Inbox.

Answer:

@Henno, your diagnosis is correct but you could have simply sorted the emails in descending order.

$inbox = imap_open($host,$user,$pass) or die('Error: ' . imap_last_error());

if( $emails = imap_search($inbox,'ALL') )
{
    arsort($emails); //JUST DO ARSORT
    foreach($emails as $email_number) {
        imap_mail_move($inbox, $email_number, 'Processed') or die('Error');
    }

}
imap_expunge($inbox);
imap_close($inbox);

Answer:

Place this at the end of your file, after you have processed any emails, this will move all found in the inbox, and move them to a folder called ‘done’.

$mbox   = imap_open('{imap.gmail.com:993/imap/ssl}INBOX', '[email protected]', 'password');
$countnum = imap_num_msg($mbox);
if($countnum > 0) {
//move the email to our saved folder
$imapresult=imap_mail_move($mbox,'1:'.$countnum,'done');
if($imapresult==false){die(imap_last_error());}
imap_close($mbox,CL_EXPUNGE);
}

Answer:

use imap_expunge() or imap_close (..., CL_EXPUNGE); but check the return value if true or false if using imap_close (..., CL_EXPUNGE);