【问题标题】:How to remove message from imap if loop break如果循环中断,如何从 imap 中删除消息
【发布时间】:2016-02-22 23:10:03
【问题描述】:

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

在某些时候,'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);

非常感谢。

【问题讨论】:

    标签: php exchange-server imap


    【解决方案1】:

    另一种方法是将delete_processed_message($x) 包裹在try-catch block 中(可以找到官方文档here)。这样,即使它抛出异常(这可能是它中断的原因),它也会继续处理其余的消息。

    代码应该是这样的

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

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

    【讨论】:

      猜你喜欢
      • 2011-03-11
      • 2011-12-29
      • 2022-06-11
      • 2015-03-27
      • 2011-01-27
      • 2015-10-03
      • 2015-07-06
      • 1970-01-01
      • 2020-04-19
      相关资源
      最近更新 更多