Arefi Clayton
Arefi Clayton

Reputation: 851

Reading a large Inbox

i am trying to create a program to delete specific e-mails from my inbox. My logic was working for me until sometimes server responds really slowly and my i get an error exception(server did not respond in time)

Using AE.Net.Mail

Here is my code :

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

I didn't get the whole inbox because there are more than 3500 e-mails in the inbox right now. It took too long and got the same exception.

Thanks

Upvotes: 1

Views: 993

Answers (2)

jstedfast
jstedfast

Reputation: 38608

A better, faster solution to this problem is to use MailKit like this:

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

Since this batches requests, things will go a LOT faster and will not hammer the server with requests.

Upvotes: 2

Arefi Clayton
Arefi Clayton

Reputation: 851

I just fixed it

Thread.Sleep(500);

since my method was working with a Thread, i just put the method sleep after every for loop. Now it works but its really slow.

Upvotes: 0

Related Questions