Not setting the property of incoming mails in MS Outlook 2010

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.

Answers


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.


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

Need Your Help

How to shut down port 3389 without losing RDP?

security windows-server-2008-r2 ports

A corporate security scan of our live web server is (correctly) reporting 3389 (the standard port for remote desktop access) as open, and requires us to close it.

Running PHPUnit in Laravel's Homestead

php laravel phpunit vagrant homestead

I'm using Homestead to serve my Laravel application. I'm trying to run PHPUnit. According to the docs:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.