Adding category to new mails
I am creating a VSTO 2007 Addin using COM. My requirement is to mark all the new mails into Blue category. I have the following code in OnNewMailEx handler
HRESULT hrGetNewMail;
_NameSpacePtr pMAPI = NULL;
hrGetNewMail = spApp->GetNamespace((_bstr_t)GetStringFromTable(147),&pMAPI);
if(FAILED(hrGetNewMail))
{
if(spApp!=NULL)
spApp.Release ();
return OPERATION_FAILED;
}
if(spApp!=NULL)
spApp.Release ();
CComBSTR EntryStoreID;
MAPIFolderPtr spMAPIFolder = NULL;
hrGetNewMail = pMAPI->GetDefaultFolder (olFolderInbox, &spMAPIFolder);
if(FAILED(hrGetNewMail))
{
if(pMAPI!=NULL)
pMAPI.Release ();
return OPERATION_FAILED;
}
hrGetNewMail = spMAPIFolder->get_StoreID (&EntryStoreID);
if(FAILED(hrGetNewMail))
{
if(spMAPIFolder!=NULL)
spMAPIFolder.Release ();
if(pMAPI!=NULL)
pMAPI.Release ();
}
if(spMAPIFolder!=NULL)
spMAPIFolder.Release ();
VARIANT varEntryStoreID;
hrGetNewMail = EntryStoreID.CopyTo (&varEntryStoreID);
if(FAILED(hrGetNewMail))
{
return OPERATION_FAILED;
}
IDispatch* spLatestMailitem;
hrGetNewMail = pMAPI->GetItemFromID (EntryID,varEntryStoreID,&spLatestMailitem);
if(FAILED(hrGetNewMail))
{
if(pMAPI!=NULL)
pMAPI.Release ();
}
if(pMAPI!=NULL)
pMAPI.Release ();
CComQIPtr <Outlook::_MailItem> spMailItem;
hrGetNewMail=spLatestMailitem->QueryInterface(&spMailItem);
HRESULT hrCat = spMailItem->put_Categories(_T("Blue Category"));
//spMailItem->put_FlagIcon(olRedFlagIcon);
hrCat = spMailItem->Save();
after execution when i open the new mails it is showing the category as Blue but in the inbox it is not marked 开发者_开发百科in any category. When i close and open the outlook the category is gone even when i open the mail which was earlier marked as blue category. however i could add a flag which is there whenever i close and open the outlook. please suggest me the problem
If the category does not exist in the master category list I don't think it keeps it. To add a category to the master category list. See for more information http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.categories.aspx
Also you example will overwrite any existing categories. you should check if a category is already specified and if so seperate the existing value and value you wish to add with a comma.
var existingCategories = item.Categories;
if (string.IsNullOrWhiteSpace(existingCategories))
{
item.Categories = "MyCategory";
}
else
{
if (item.Categories.Contains("MyCategory") == false)
{
item.Categories = existingCategories + ", MyCategory";
}
}
item.Save();
精彩评论