mhesabi
mhesabi

Reputation: 1140

C# List all email addresses in MS Exchange

I need to get list of all emails from exchange/active directory.
Whether emails like [email protected] or email groups like all-contacts or CEO which they includes couple of email addresses.
this is my code so far:

DirectoryEntry de = new DirectoryEntry(ad_path);
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(&(objectClass=addressBookContainer)(CN=All Global Address Lists,CN=Address Lists Container,CN=First Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=mydomain,DC=local))";
SearchResultCollection ss = ds.FindAll(); // count = 0

Upvotes: 0

Views: 2307

Answers (1)

Sebastian
Sebastian

Reputation: 379

You will not get the email addresses from the Directory Objects as these are only configuration objects. If you want to get all mail addresses in your org you could query the following (note that there is a limited result size by default):

        DirectoryEntry de = new DirectoryEntry();
        DirectorySearcher ds = new DirectorySearcher(de);
        ds.PropertiesToLoad.Add("proxyAddresses");
        ds.Filter = "(&(proxyAddresses=smtp:*))";
        SearchResultCollection ss = ds.FindAll(); // count = 0

        foreach (SearchResult sr in ss)
        {
            // you might still need to filter out other addresstypes, ex: sip:
            foreach (String addr in sr.Properties["proxyAddresses"])
                Console.WriteLine(addr);
            //or without the 'smtp:' prefix Console.WriteLine(addr.SubString(5));

        }

If you would like to get the contents of specific exchange address lists, you can modify your filter and replace it with the value of the 'purportedSearch'-Property of that list, for example:

(&(mailNickname=*)(|(objectClass=user)(objectClass=contact)(objectClass=msExchSystemMailbox)(objectClass=msExchDynamicDistributionList)(objectClass=group)(objectClass=publicFolder)))

which is the default Filter for "Default Global Address List".

You can also enumerate all AddressBookContainer objects in (CN=All Global Address Lists,CN=Address Lists Container,CN=First Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=mydomain,DC=local) to do a query with each 'purportedSearch'-Property.

Upvotes: 1

Related Questions