Brian Kraemer
Brian Kraemer

Reputation: 453

Find all e-mail addresses associated with a user in active directory using C#

I'm trying to get c# to return all e-mail addresses associated with a user in the Active Directory. Many of our users have mutliple e-mail addresses and I need to be able to get a list of all addresses associated with a single user. I'm using the code block below but it only returns one e-mail address. Any help would be appreciated.

string username = "user";
string domain = "domain";
List<string> emailAddresses = new List<string>();
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domain);
UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, username);

// Add the "mail" entry 
emailAddresses.Add(user.EmailAddress);

foreach (String item in emailAddresses)
{
    DropDownList1.Items.Add(item);
}

Upvotes: 1

Views: 3796

Answers (2)

Ashigore
Ashigore

Reputation: 4678

In active directory the mail attribute (UserPrincipal.EmailAddress) only holds the user's primary e-mail address. To retrieve all a user's addresses you must read and parse the msExchShadowProxyAddresses attribute which contains all addresses not just SMTP ones (like CIP for example).

Something like this should work:

static List<string> GetUserEmailAddresses(string username, string domain)
{
    using (PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domain))
    using (UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, username))
    {
        return ((DirectoryEntry)user.GetUnderlyingObject())
            .Properties["msExchShadowProxyAddresses"]
            .OfType<string>()
            .Where(s => !string.IsNullOrWhiteSpace(s) && s.StartsWith("smtp:", StringComparison.OrdinalIgnoreCase))
            .ToList();
    }
}

Upvotes: 2

jonnep
jonnep

Reputation: 285

You will need to use System.DirectoryServices namespace to search the Active Directory for the user that you're looking for.

Once found, you can grab any properties attached to that particular user.

See the following links on how to search in an active directory.

http://msdn.microsoft.com/en-us/library/ms180885(v=vs.80).aspx http://msdn.microsoft.com/en-us/library/ms973834.aspx

Upvotes: 1

Related Questions