阅读大型收件箱

Reading a large Inbox

我正在尝试创建一个程序来从我的收件箱中删除特定的电子邮件。 我的逻辑对我有用,直到有时服务器响应非常缓慢并且我收到错误异常(服务器未及时响应)

使用AE.Net.Mail

这是我的代码:

        private void GetMessages() 
    {
        ImapClient client = new ImapClient();
        client.Connect("imap-mail.outlook.com", 993, true, false);
        client.Login("mail", "password");
        client.SelectMailbox("INBOX");
        client.ServerTimeout = 0; // I just assumed 0 might be never.
        client.IdleTimeout = 0;
        int mcount = client.GetMessageCount();
        for (int i = 0; i < mcount; i++)
        {
            lblStatus.BeginInvoke(new MethodInvoker(delegate { lblStatus.Text = "Proccessed " + i.ToString() + " / " + mcount.ToString() + " e-mail messages. "; }));
            MailMessage msg = client.GetMessage(i, true);
            if (msg.From.Address == txtMailToDelete.Text)
            {
                deletedcount++;
                client.DeleteMessage(msg);
                lblDeletedMessages.BeginInvoke(new MethodInvoker(delegate { lblDeletedMessages.Text = "Deleted " + deletedcount.ToString() + " messages. "; }));
            }
        }
    }

我没有收到整个收件箱,因为现在收件箱中有 3500 多封电子邮件。耗时太久,出现同样的异常。

谢谢

我刚修好了

Thread.Sleep(500);

因为我的方法是使用线程,所以我只是在每个 for 循环之后让方法休眠。现在可以用了,但是真的很慢。

解决这个问题的更好、更快的方法是像这样使用 MailKit

private void DeleteMessages () 
{
    using (var client = new ImapClient ()) {
        client.Connect ("imap-mail.outlook.com", 993, true);
        client.Authenticate ("mail", "password");

        client.Inbox.Open (FolderAccess.ReadWrite);

        // Search for messages that match the From address.
        var uids = client.Inbox.Search (SearchQuery.FromContains (txtMailToDelete.Text));

        // Mark the messages for deletion.
        client.Inbox.AddFlags (uids, MessageFlags.Deleted, true);

        // if the server supports the UIDPLUS extension, issue a "UID EXPUNGE"
        // command to purge the messages we just marked for deletion.
        if (client.Capabilities.HasFlag (ImapCapabilities.UidPlus))
            client.Inbox.Expunge (uids);

        client.Disconnect (true);
    }
}

由于这种批处理请求,事情会进行得更快,并且不会用请求冲击服务器。