简体   繁体   中英

How to get a user's e-mail address from Active Directory?

I am trying to get a user's email address in AD without success.

String account = userAccount.Replace(@"Domain\", "");
DirectoryEntry entry = new DirectoryEntry();

try {
    DirectorySearcher search = new DirectorySearcher(entry);

    search.PropertiesToLoad.Add("mail");  // e-mail addressead

    SearchResult result = search.FindOne();
    if (result != null) {
        return result.Properties["mail"][0].ToString();
    } else {
        return "Unknown User";
    }
} catch (Exception ex) {
    return ex.Message;
}

Can anyone see the issue or point in the right direction?

Disclaimer: This code doesn't search for a single exact match , so for domain\\j_doe it may return domain\\j_doe_from_external_department 's email address if such similarly named account also exists. If such behaviour is undesirable, then either use a samAccountName filter intead of an anr one used below or filter the results additionally.

I have used this code successfully (where "account" is the user logon name without the domain (domain\\account):

// get a DirectorySearcher object
DirectorySearcher search = new DirectorySearcher(entry);

// specify the search filter
search.Filter = "(&(objectClass=user)(anr=" + account + "))";

// specify which property values to return in the search
search.PropertiesToLoad.Add("givenName");   // first name
search.PropertiesToLoad.Add("sn");          // last name
search.PropertiesToLoad.Add("mail");        // smtp mail address

// perform the search
SearchResult result = search.FindOne();

You guys are working too hard:

// Look up the current user's email address
string eMail =  UserPrincipal.Current.EmailAddress;

You can try the below GetUserEmail method. If You are looking out to find the email address for logged-in user in MVC then call the GetUserEmail() function with User.Identity.Name

using System.DirectoryServices;
using System.Linq;

public string GetUserEmail(string UserId)
    {

        var searcher = new DirectorySearcher("LDAP://" + UserId.Split('\\').First().ToLower())
        {
            Filter = "(&(ObjectClass=person)(sAMAccountName=" + UserId.Split('\\').Last().ToLower() + "))"
        };

        var result = searcher.FindOne();
        if (result == null)
            return string.Empty;

        return result.Properties["mail"][0].ToString();

    }

GetUserEmail(User.Identity.Name) //Get Logged in user email address

You forgot a filter.

Try adding this before calling FindOne:

search.Filter = String.Format("(sAMAccountName={0})", account);

You need to add references for System.DirectoryServices.AccountManagement and include this same references in your using statement. Now you will have access to the current users login details as listed below include the email address.

string loginname = Environment.UserName;
string firstname = UserPrincipal.Current.GivenName;
string lastname = UserPrincipal.Current.Surname;
string name = UserPrincipal.Current.Name;
string eMail = UserPrincipal.Current.EmailAddress;

What about this

public string GetEmailFromSamAccountName(string samAccountName, string domain="YOURCOMPANY")
{
   using (var principalContext = new PrincipalContext(ContextType.Domain, domain))
   {
      var userPrincipal = UserPrincipal.FindByIdentity(principalContext, samAccountName);
      return userPrincipal.EmailAddress;
   }
}

Also, where do you pull the username from (stored, user input, current identity)? A username can change (be renamed) easily - the SID/Windows Logon Identity on the other hand does not change - so you would be better off doing filters/searches by SID rather than samaccountname - if possible and/or needed design-wise...

update : fredrick nailed it....

Jakob is right. You need to filter your search. You can do all sorts of and s and or s there too if you need to, but I think sAMAccountName is enough. You might want to fire up the ADSI tool (it's in the resource kit I think), which lets you walk AD like the registry. it's great for looking at properties. Then find a user, work out what prop you want (mail in this case) and what it's primary key is - sAMAccountName is a good one, but you may also want to filter on the node type.

I'm on a mac, so I can't check it for you, but each node in AD has a type, and you can add that to your filter. I think it looks like this:

((sAMAccountName=bob) & (type=User))

Again, check that - I know it's not type=user, but something LIKE that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM