如果循环中断,如何从imap中删除消息


How to remove message from imap if loop break

我正在使用php从exchange邮箱读取消息。下面只是一个简单的脚本,而不是一个真实的例子。

在某个时刻,"for"循环有时会中断,我正在解决这些问题。

如果有10条消息,并且循环中断在最后一条消息上,那么其他9条本应删除的消息将不会被删除,因为无法到达代码中断到删除。

有没有解决办法,所以即使代码坏了,我仍然可以删除已经处理删除的正确电子邮件。

    //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);

非常感谢。

一种替代方案是将delete_processed_message($x)封装在try-catch块中(可以在此处找到官方文档)。这样,即使它抛出异常(这可能是它崩溃的原因),它也会继续处理其余的消息。

代码应该看起来像这个

...
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";
   }
}
...

就像这个问题中解释的那样,在for循环中使用try-catch可以确保for完成。