Поделиться через


Определение глобального списка адресов или набора списков адресов с помощью store

Во время сеанса Microsoft Outlook, где в профиле определены несколько учетных записей Microsoft Exchange, с магазином может быть связано несколько списков адресов. В этом разделе содержатся два примера кода, в которые показано, как получить глобальный список адресов для данного хранилища и как получить все объекты AddressList , связанные с данным хранилищем. В каждом из этих примеров кода конкретное хранилище представляет собой хранилище для текущей папки, отображаемой в активном обозревателе, но алгоритм получения глобального списка адресов или набора списков адресов для хранилища применяется к любому хранилищу Exchange.

Следующий пример управляемого кода написан на C#. Для запуска примера управляемого кода для .NET Framework, который вызывает модель COM, необходимо использовать сборку взаимодействия, которая определяет и сопоставляет управляемые интерфейсы с объектами COM в библиотеке типов объектной модели. Для Outlook можно использовать Visual Studio и первичную сборку взаимодействия Outlook (PIA). Перед запуском примеров управляемого кода для Outlook 2013 убедитесь, что вы установили Outlook 2013 PIA и добавили ссылку на компонент Microsoft Outlook 15.0 Object Library в Visual Studio. В классе надстройки ThisAddIn Outlook следует использовать следующий код (с помощью средств разработчика Office для Visual Studio). Объект Application в коде должен быть доверенным объектом Application Outlook, предоставленным объектом ThisAddIn.Globals. Дополнительные сведения об использовании Outlook PIA для разработки управляемых решений Outlook см. в статье Справочник по основной сборке взаимодействия Outlook на веб-сайте MSDN.

Первый пример кода содержит DisplayGlobalAddressListForStore метод и функцию GetGlobalAddressList . Метод DisplayGlobalAddressListForStore отображает глобальный список адресов, связанный с текущим хранилищем, в диалоговом окне Выбор имен . DisplayGlobalAddressListForStore сначала получает текущее хранилище. Если текущее хранилище является хранилищем Exchange, вызывается GetGlobalAddressList для получения глобального списка адресов, связанного с текущим хранилищем. GetGlobalAddressList использует объект PropertyAccessor и свойство MAPI , https://schemas.microsoft.com/mapi/proptag/0x3D150102чтобы получить идентификаторы пользовательского интерфейса списка адресов и текущего хранилища. GetGlobalAddressList определяет список адресов, связанный с хранилищем, если совпадают идентификаторы UID, а список адресов — глобальный список адресов, если его свойство AddressListType имеет значение olExchangeGlobalAddressList. Если вызов выполнен GetGlobalAddressList успешно, DisplayGlobalAddressListForStore использует объект SelectNamesDialog для отображения возвращенного глобального списка адресов в диалоговом окне Выбор имен .

void DisplayGlobalAddressListForStore() 
{ 
    // Obtain the store for the current folder 
    // as the current store. 
    Outlook.Folder currentFolder = 
        Application.ActiveExplorer().CurrentFolder 
        as Outlook.Folder; 
    Outlook.Store currentStore = currentFolder.Store; 
 
    // Check if the current store is Exchange. 
    if (currentStore.ExchangeStoreType != 
        Outlook.OlExchangeStoreType.olNotExchange) 
    { 
        Outlook.SelectNamesDialog snd =  
            Application.Session.GetSelectNamesDialog(); 
 
        // Try to get the Global Address List associated  
        // with the current store. 
        Outlook.AddressList addrList =  
            GetGlobalAddressList(currentStore); 
        if (addrList != null) 
        { 
            // Display the Global Address List in the  
            // Select Names dialog box. 
            snd.InitialAddressList = addrList; 
            snd.Display(); 
        } 
    } 
} 
 
public Outlook.AddressList GetGlobalAddressList(Outlook.Store store) 
{ 
    // Property string for the UID of a store or address list. 
    string  PR_EMSMDB_SECTION_UID =  
        @"https://schemas.microsoft.com/mapi/proptag/0x3D150102"; 
 
    if (store == null) 
    { 
        throw new ArgumentNullException(); 
    } 
 
    // Obtain the store UID using the property string and  
    // property accessor on the store. 
    Outlook.PropertyAccessor oPAStore = store.PropertyAccessor; 
 
    // Convert the store UID to a string value. 
    string storeUID = oPAStore.BinaryToString( 
        oPAStore.GetProperty(PR_EMSMDB_SECTION_UID)); 
 
    // Enumerate each address list associated 
    // with the session. 
    foreach (Outlook.AddressList addrList  
        in Application.Session.AddressLists) 
    { 
        // Obtain the address list UID and convert it to  
        // a string value. 
        Outlook.PropertyAccessor oPAAddrList =  
            addrList.PropertyAccessor; 
        string addrListUID = oPAAddrList.BinaryToString( 
            oPAAddrList.GetProperty(PR_EMSMDB_SECTION_UID)); 
 
        // Return the address list associated with the store 
        // if the address list UID matches the store UID and 
        // type is olExchangeGlobalAddressList. 
        if (addrListUID == storeUID && addrList.AddressListType == 
            Outlook.OlAddressListType.olExchangeGlobalAddressList) 
        { 
            return addrList; 
        } 
    } 
    return null; 
} 

Второй пример кода содержит EnumerateAddressListsForStore метод и GetAddressLists функцию. Метод EnumerateAddressListsForStore отображает тип и порядок разрешения каждого списка адресов, определенного для текущего хранилища. EnumerateAddressListsForStoreсначала получает текущее хранилище, а затем вызывает GetAddressLists для получения платформа .NET Framework универсального объекта List, содержащего объекты AddressList для текущего хранилища. GetAddressLists перечисляет каждый список адресов, определенный для сеанса, использует объект PropertyAccessor и именованное свойство MAPI , https://schemas.microsoft.com/mapi/proptag/0x3D150102чтобы получить идентификаторы пользовательского интерфейса списка адресов и текущего хранилища. GetGlobalAddressList определяет список адресов, связанный с хранилищем, если их идентификаторы UID совпадают, и возвращает набор списков адресов для текущего хранилища. Затем EnumerateAddressListsForStore применяет свойства AddressListType и ResolutionOrder объекта AddressList, чтобы показать тип и порядок разрешения для каждого возвращенного списка адресов.

private void EnumerateAddressListsForStore() 
{ 
    // Obtain the store for the current folder 
    // as the current store. 
    Outlook.Folder currentFolder = 
       Application.ActiveExplorer().CurrentFolder 
       as Outlook.Folder; 
    Outlook.Store currentStore = currentFolder.Store; 
 
    // Obtain all address lists for the current store. 
    List<Outlook.AddressList> addrListsForStore =  
        GetAddressLists(currentStore); 
    foreach (Outlook.AddressList addrList in addrListsForStore) 
    { 
        // Display the type and resolution order of each  
        // address list in the current store. 
        Debug.WriteLine(addrList.Name  
            + " " + addrList.AddressListType.ToString() 
            + " Resolution Order: " + 
            addrList.ResolutionOrder); 
     }  
} 
 
public List<Outlook.AddressList> GetAddressLists(Outlook.Store store) 
{ 
    List<Outlook.AddressList> addrLists =  
        new List<Microsoft.Office.Interop.Outlook.AddressList>(); 
 
    // Property string for the UID of a store or address list. 
    string PR_EMSMDB_SECTION_UID = 
        @"https://schemas.microsoft.com/mapi/proptag/0x3D150102"; 
 
    if (store == null) 
    { 
        throw new ArgumentNullException(); 
    } 
 
    // Obtain the store UID and convert it to a string value. 
    Outlook.PropertyAccessor oPAStore = store.PropertyAccessor; 
    string storeUID = oPAStore.BinaryToString( 
        oPAStore.GetProperty(PR_EMSMDB_SECTION_UID)); 
 
    // Enumerate each address list associated 
    // with the session. 
    foreach (Outlook.AddressList addrList 
        in Application.Session.AddressLists) 
    { 
        // Obtain the address list UID and convert it to  
        // a string value. 
        Outlook.PropertyAccessor oPAAddrList = 
            addrList.PropertyAccessor; 
        string addrListUID = oPAAddrList.BinaryToString( 
            oPAAddrList.GetProperty(PR_EMSMDB_SECTION_UID)); 
         
        // Add the address list to the resultant set of address lists 
        // if the address list UID matches the store UID. 
        if (addrListUID == storeUID) 
        { 
            addrLists.Add(addrList); 
        } 
    } 
    // Return the set of address lists associated with the store. 
    return addrLists; 
} 

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.