0

I am setting the property (for making them As Read and with High Importance) of the mail those are coming to the MS Outlook 2010 inbox using below code -

 Microsoft.Office.Interop.Outlook.Application myApp = new Microsoft.Office.Interop.Outlook.Application();
 Microsoft.Office.Interop.Outlook.NameSpace mapiNameSpace = myApp.GetNamespace("MAPI");
 Microsoft.Office.Interop.Outlook.MAPIFolder myInbox = mapiNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);     

 int i = myInbox.Items.Count;
 ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[i]).UnRead = false;
 ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[i]).Importance = OlImportance.olImportanceHigh;

This works fine when only one mail comes at a time (I can see the mail as Read and with High Importance) after the code execution but when three or four mails coming at a time then it set the property of only one mail not for all the three or four mails.

Please suggest.

Nitendra Jain
  • 489
  • 1
  • 7
  • 24

2 Answers2

0

You can use the ItemAdd event of the Items property of the folder:

Items inboxItems = myInbox.Items;
inboxItems.ItemAdd += HandleItemAdded;

private void HandleItemAdded(object item)
{
    MailItem mail = item as MailItem;
    if (mail == null) { return; }
    mail.UnRead = false;
    mail.Importance = OlImportance.olImportanceHigh;
}
cremor
  • 6,669
  • 1
  • 29
  • 72
0

Remember to save the message after setting any property. Most importantly, your code uses multiple dot notation - for each ".", you get back a brand new COM object, so you end up setting Importance property on an object different from the one used to set the UnRead property.

int i = myInbox.Items.Count;
MailItem msg = (Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[i];
msg.UnRead = false;
msg.Importance = OlImportance.
msg.Save();

Another problem is that you assume that the last item in the Items collection is the latest one. This is not generally true. As cremor suggested, use Items.ItemAdd event, but still do not forget to save the message.

Dmitry Streblechenko
  • 62,942
  • 4
  • 53
  • 78