0

I am using php to read messages from exchange mailbox. The below is just a simple script not a real example.

At some point the 'for' loop sometimes break and I am in process of fixing these issues.

If there are 10 messages and the loop break on the last one the other 9 messages which supposed to be removed will not be removed because the code break to the expunge is not reach.

Is there a work around so even if the code breaks i could still remove the correct emails which have already been processed for deletion.

    //checking how many messages are in the mailbox
    $total = imap_num_msg($inbox);
    //if there are any messages then process them
    if ( $total > 0){
    echo "\nAnalysing Mailbox\n";

    for ($x=$total; $x>0; $x--){
    //doing some work here 

    delete_processed_message($x);
    }

    echo "Please wait, expunging old messages\n";
    imap_expunge($inbox);
    echo "Please wait, disconnecting from mail box\n";
    imap_close($inbox);

Many Thanks.

Rafal Zdziech
  • 29
  • 1
  • 6

1 Answers1

0

One alternative would be to wrap you delete_processed_message($x) in a try-catch block (official documentation can be found here). That way, even if it throws an exception (which is probably the reason it's breaking), it'll continue with the rest of the messages.

The code should look like this

...
for ($x=$total; $x>0; $x--){
    //doing some work here 
   try {
        delete_processed_message($x);
   } 
   catch (Exception $e) {
        //Here you can log it to a file, or simply echo it 
       echo 'Caught exception: ',  $e->getMessage(), "\n";
   }

}
...

And like it was explained in this question, using the try-catch inside the for loop makes sure the for finishes.

Community
  • 1
  • 1
Squirrel
  • 392
  • 7
  • 15