2

I'm writing a code to access outlook and process the Unread Mails one by one and mark them as Read (so it won't run on the same mails).

The issue is that it's unable to read all the unread mails. (e.g) suppose in Inbox I'm having 10 mails but it works only for 5 mails. It's processing only half of the mail counts.

After marking as Read, count is reducing but forloop is not iterating for all unread mails, skipping the mails

I wrote it like this:

Outlook.Application outlookApp = new Outlook.Application();

        Outlook._NameSpace oNS;
        Outlook.MAPIFolder oFolder;
        Outlook._Explorer oExp;

        outlookApp = new Outlook.Application();
        oNS = (Outlook._NameSpace)outlookApp.GetNamespace("MAPI");
        oFolder = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
        oExp = oFolder.GetExplorer(false);
        oNS.Logon(Missing.Value, Missing.Value, false, true);

        Outlook.Items items = oFolder.Items.Restrict("[Unread]=true");

        int mailcount = items.Count;

        foreach (Microsoft.Office.Interop.Outlook.MailItem mailItem in oFolder.Items)
        {
            if (mailItem.UnRead) // I only process the mail if unread
            {
                Console.WriteLine("Accounts: {0}", mailItem.Subject);
                mailItem.UnRead = false;                   
            }
        }

Am i missing anything ?Could you please any one help for this?

Bizhan
  • 16,157
  • 9
  • 63
  • 101

1 Answers1

2

Every time that you mark one item as read your 'items' collection is affected (reduced) and that was the problem.

OutLook.Application oApp;
OutLook._NameSpace oNS;
OutLook.MAPIFolder oFolder;
OutLook._Explorer oExp;

oApp = new OutLook.Application();
oNS = (OutLook._NameSpace)oApp.GetNamespace("MAPI");
oFolder = oNS.GetDefaultFolder(OutLook.OlDefaultFolders.olFolderInbox);
oExp = oFolder.GetExplorer(false);
oNS.Logon(Missing.Value, Missing.Value, false, true);

OutLook.Items items = oFolder.Items.Restrict("[Unread]=true");

// Switched to for, https://stackoverflow.com/questions/4317850/do-i-need-to-release-the-com-object-on-every-foreach-iteration#4317878
for (int i = items.Count; i >= 1; i--)
{
     var mail = items[i];

     if (mail.UnRead)
     {
          mail.UnRead = false;
          mail.Save();
     }

     Marshal.ReleaseComObject(mail);
 }

 Marshal.ReleaseComObject(items);
Rui Fernandes
  • 270
  • 1
  • 11