以编程方式将联系人添加到通讯组

时间:2013-12-21 21:09:40

标签: c# com outlook office-interop

我真的陷入了这个问题,搜索并没有让我受益匪浅。我找到的大多数答案都是获取联系人而不是添加它们或使用LDAP。

我能做的最好的事情是显示将人员添加到分发列表的窗口,但我无法以编程方式执行该部分

这是我最好的尝试:

Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
NameSpace oNS = oApp.GetNamespace("MAPI");
//Get Global Address List.
AddressLists oDLs = oNS.AddressLists;
AddressList oGal = oDLs["Global Address List"];
AddressEntries oEntries = oGal.AddressEntries;
AddressEntry oDL = oEntries["MyDistributionList"];

//Get Specific Person
SelectNamesDialog snd = oApp.Session.GetSelectNamesDialog();
snd.NumberOfRecipientSelectors = OlRecipientSelectors.olShowTo;
snd.ToLabel = "D/L";
snd.ShowOnlyInitialAddressList = true;
snd.AllowMultipleSelection = false;
//snd.Display();
AddressEntry addrEntry = oDL;
if (addrEntry.AddressEntryUserType == Microsoft.Office.Interop.Outlook.OlAddressEntryUserType.olExchangeDistributionListAddressEntry)
{
    ExchangeDistributionList exchDL = addrEntry.GetExchangeDistributionList();
    AddressEntries addrEntries = exchDL.GetExchangeDistributionListMembers();

    string name = "John Doe";
    string address = "John.Doe@MyCompany.com";
    exchDL.GetExchangeDistributionListMembers().Add(OlAddressEntryUserType.olExchangeUserAddressEntry.ToString(), name, address);
    exchDL.Update(Missing.Value);
}

使用此我可以访问分发列表,但我在

上得到“书签无效”例外
exchDL.GetExchangeDistributionListMembers().Add(OlAddressEntryUserType.olExchangeUserAddressEntry.ToString(), name, address);

线。

我可以访问上述列表。

编辑: Example

1 个答案:

答案 0 :(得分:3)

问题在于,当您使用Outlook API时,您将其功能用作用户,而不是管理员。
更重要的是,您只能通过Outlook UI执行操作

Outlook不允许您修改通讯组列表,因此您将无法使用Outlook API执行此操作。

有两种可能的方法:

  1. 使用NetApi函数NetGroupAddUserNetLocalGroupAddMembers,具体取决于该组是本地组还是全局组。这将需要使用P / Invoke导入这些函数,并且不适用于通用组。
  2. 2。使用LDAP查找所需的组,并添加所需的用户。这可以使用System.DirectoryServices命名空间完成,如下所示:

    using(DirectoryEntry root = new DirectoryEntry("LDAP://<host>/<DC root DN>"))
    using(DirectorySearcher searcher = new DirectorySearcher(root))
    {
        searcher.Filter = "(&(objName=MyDistributionList))";
        using(DirectoryEntry group = searcher.findOne())
        {
            searcher.Filter = "(&(objName=MyUserName))";
            using(DirectoryEntry user = searcher.findOne())
            {
                 group.Invoke("Add", user.Path);
            }
        }
    }
    

    这些只是包装旧的COM ADSI接口,这就是我使用group.Invoke()的原因。它需要更多练习,但比NetApi功能更强大。