以编程方式设置Outlook mailitem的类别?

时间:2012-02-06 15:27:01

标签: outlook office-interop

似乎没有太多信息或任何良好的代码示例用于以编程方式设置Outlook 2007 MailItem的类别。

MSDN has a limited page,并提及使用VB的拆分功能,或多或少说“你自己从这里开始,所以自己解决

据我所知,我们将类别操作为mailitem的逗号分隔字符串属性。看起来有点原始,是不是都有它呢?

每个人都只是挖出他们的字符串函数库并解析Categories属性,当为一个mailitem设置多个类别并且(天堂禁止)类别被重命名时,相信不会陷入困境吗?

2 个答案:

答案 0 :(得分:19)

您可以选择以任何方式操纵逗号分隔的字符串。要插入一个类别,我通常会检查当前字符串是否为空,然后只是分配它。如果类别不为null,那么如果它尚不存在则附加它。要删除项目,我只需用空字符串替换类别名称。

添加类别

 var customCat = "Custom Category";
 if (mailItem.Categories == null) // no current categories assigned
   mailItem.Categories = customCat;
 else if (!mailItem.Categories.Contains(customCat)) // insert as first assigned category
   mailItem.Categories = string.Format("{0}, {1}", customCat, mailItem.Categories);

删除类别

var customCat = "Custom Category";
if (mailItem.Categories.Contains(customCat))
  mailItem.Categories = mailItem.Categories.Replace(string.Format("{0}, ", customCat), "").Replace(string.Format("{0}", customCat), "");

有很多方法可以操作字符串 - 他们只是选择将序列化数据结构保持在简单的下面。

我倾向于在加载项启动期间创建自己的类别以验证它们是否存在。当然 - 类别重命名是一个问题,但如果您确保每次加载项加载时都存在类别,则至少可以确保某种程度的有效性。

要管理Outlook类别,您可以使用ThisAddIn.Application.Session.Categories

var customCat = "Custom Category";
if (Application.Session.Categories[customCat] == null)  
  Application.Session.Categories.Add(customCat, Outlook.OlCategoryColor.olCategoryColorDarkRed);

答案 1 :(得分:0)

只需在@SilverNija-MSFT帖子中包含最后一个信息。之后做这样的事情:

 var customCat = "Custom Category";
 if (mailItem.Categories == null) // no current categories assigned
   mailItem.Categories = customCat;
 else if (!mailItem.Categories.Contains(customCat)) // insert as first assigned category
   mailItem.Categories = string.Format("{0}, {1}", customCat, mailItem.Categories);

不要忘记,这是最重要的,以这种方式更新mailItem的实例:

mailItem.Save();

因为存在一个问题,有时一堆邮件项目在循环中时不会更新,因此它可以解决我的问题。