Search code examples
c#outlook-2010

Is there a better way to filter mails based on date?


Well I have run into a problem.

I am using the MS outlook API using C # to generate a few excel based reports from the emails that I receive.

Now initially when I started this, it was OK as the number emails were a little less in the folder. Now after a few days, the number has gone into thousands.

 Application app = null;
            _NameSpace ns = null;
            MailItem item = null;
            MAPIFolder inboxFolder = null;
            MAPIFolder subFolder = null;

            DateTime MyDateTime;
            MyDateTime = new DateTime();
            MyDateTime = DateTime.ParseExact(dateFilter, "yyyy-MM-dd HH:mm tt", null);

            try
            {
                app = new Application();
                ns = app.GetNamespace("MAPI");
                ns.Logon(null, null, false, false);

                inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
                subFolder = inboxFolder.Folders["Alerts"];


                for (int i = 1; i <= subFolder.Items.Count; i++)
                {
                    item = (Microsoft.Office.Interop.Outlook.MailItem)subFolder.Items[i];

                    string subject = item.Subject;
                    DateTime sent = item.SentOn;

                    if (item.SentOn > MyDateTime && item.SentOn < MyDateTime.AddDays(1))
{//Do some logging
}}

Now the issue with the above code is that it starts searching from the last email received. This is causing it to increase the time it takes to reach the "filter".

I need suggestions to improve my code, if any.

Thanks for reading me out.


Solution

  • Before your loop, get a collection of items from subFolder filtered by the Restrict method. You can use your date ranges in the filter string that you use (I've not written it here since I'm not in a position to test it and don't want to mislead you - a search should give plenty of examples). Then just loop/iterate over the resulting collection which should then contain just the items you need.

    Microsoft.Office.Interop.Outlook.Items restrictedItems = subFolder.Items.Restrict("*filter*");
    
    for (int i = 1; i <= restrictedItems.Count; i++)...