我正在尝试创建一个程序来从我的收件箱中删除特定的电子邮件。 我的逻辑正在为我工作,直到有时服务器响应非常慢并且我得到错误异常(服务器没有及时响应)
使用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封电子邮件。花了太长时间才得到同样的例外。
由于
答案 0 :(得分:2)
更好,更快解决此问题的方法是使用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);
}
}
由于批量请求,事情会更快,并且不会随着请求而破坏服务器。
答案 1 :(得分:0)
我刚修好了
Thread.Sleep(500);
因为我的方法是使用Thread,所以我只是在每个for循环之后将方法置于休眠状态。现在它可以工作,但它真的很慢。