How can I query an ActiveDirectory user by email address? A given user can have multiple emails such as both [email protected] and [email protected]. For a given email, how can I get back the A/D user?
I'm programming in C#.
You can search your AD with following code:
DirectoryEntry adEntry = null;
private void SetADInfoAndCredentials()
{
adEntry = new DirectoryEntry("LDAP://" + ad_textBox.Text);
adEntry.Username = user_textBox.Text;
adEntry.Password = pw_textBox.Text;
}
private void SearchForMailInAD()
{
DirectorySearcher adSearcher = new DirectorySearcher(adEntry);
adSearcher.Filter = ("mail=" + mail_textBox.Text);
SearchResultCollection coll = adSearcher.FindAll();
foreach (SearchResult item in coll)
{
foundUsers_listBox.Items.Add(item.GetDirectoryEntry());
}
}
€: This will search for the mail address in proxyAddresses which hosts all mail addresses
public static SearchResultCollection FindAccountByEmail(string pEmailAddress)
{
string filter = string.Format("(proxyaddresses=SMTP:{0})", email);
using (DirectoryEntry gc = new DirectoryEntry("LDAP:"))
{
foreach (DirectoryEntry z in gc.Children)
{
using (DirectoryEntry root = z)
{
using (DirectorySearcher searcher = new DirectorySearcher(root, filter, new string[] { "proxyAddresses", "objectGuid", "displayName", "distinguishedName" }))
{
searcher.ReferralChasing = ReferralChasingOption.All;
SearchResultCollection result = searcher.FindAll();
return result;
}
}
}
}
return null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With