1
votes

I use this function to access LDAP and get user's email address attribute

public string Login(string userName, string password)
{
        DirectoryEntry de = new DirectoryEntry();

        de.Path = "LDAP://000.000.0.00"; // forexample
        de.AuthenticationType = AuthenticationTypes.Secure;
        de.Username = userName;
        de.Password = password;

        DirectorySearcher search = new DirectorySearcher(de);
        search.Filter = "(&(samaccountname=" + userName + "))";
        search.ReferralChasing = ReferralChasingOption.All;

        SearchResult resultCol = search.FindOne();
        string mailProperty="";
        if (resultCol != null)
        {
            if (resultCol.Properties["mail"] != null && resultCol.Properties["mail"].Count > 0)
            {
                mailProperty = resultCol.Properties["mail"][0].ToString();
            }
        }

        return mailProperty;
    }

I didn't get mail attribute in the list of returned attributes, that is the list of attributes I got which doesn't contain the mail attribute

  • givenname , samaccountname , cn , pwdlastset , whencreated , badpwdcount
    , displayname , lastlogon , samaccounttype
    , countrycode , objectguid , usnchanged
    , whenchanged , name , objectsid
    , logoncount , badpasswordtime , accountexpires
    , primarygroupid , objectcategory , userprincipalname
    , useraccountcontrol , description , dscorepropagationdata , distinguishedname , objectclass , usncreated , lastlogontimestamp , adspath , lastlogoff , instancetype , codepage , sn
1
You can maybe use userPrincipalName. In most cases it is equal to the mail property.abydal
userPrincipalName returns null most of times, i can't relay on it, the active directory contains mail address which is not null for all users, but I cant get it by c#Abraham Josef
are you sure email is populated in your AD?BugFinder
yes active directory contains mailAbraham Josef
I see that in my code I use a more specific filter to make sure that its actually a user I am getting back. It looks like this (&(&(objectClass=user)(!(objectClass=computer)))(samaccountname=" + username + "))abydal

1 Answers

1
votes

After investigation with the system admin, I found that to retrieve mail attribute from LDAP user has to have both accounts, the normal active directory account and mail box account (exchange), if user does not have mailbox account so any LDAP query will not retrieve the mail attribute