Define AD Security Group Email Address

In AD here at work, there are several security groups that are included in the mail. I use the System.DirectoryServices.AccountManagement namespace as follows:

List<GroupPrincipal> result = new List<GroupPrincipal>(); using (PrincipalContext domain = new PrincipalContext(ContextType.Domain, userinfo[0])) using (UserPrincipal user = UserPrincipal.FindByIdentity(domain, username)) { if (user != null) { PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups(); int totalGroupCounter = 0; StringBuilder output = new StringBuilder(); List<GroupPrincipal> securityGroups = new List<GroupPrincipal>(); List<GroupPrincipal> distributionGroups = new List<GroupPrincipal>(); foreach (Principal group in groups) { totalGroupCounter++; if (((GroupPrincipal)group).IsSecurityGroup.Value) securityGroups.Add((GroupPrincipal)group); else distributionGroups.Add((GroupPrincipal)group); } } } 

Armed with this information, what's the right way to find a group email address?

+4
source share
3 answers

I consider marc_s an expert on active directory topics, but I also had a security group that had an email address associated with it. Here's how I could get an email from him:

 private void GetGroupEmail() { using (var searcher = new DirectorySearcher()) { searcher.Filter = "(&(objectClass=group))"; searcher.SearchRoot = entry; searcher.PropertiesToLoad.Add("mail"); foreach (SearchResult sr in searcher.FindAll()) { var email = GetSearchResultProperty(sr, "mail"); } } } private string GetSearchResultProperty(SearchResult sr, string propertyName) { var property = sr.Properties[propertyName]; if (property != null && property.Count > 0) { return (string)property[0]; } else { return null; } } 
0
source

AccountManagement libraries limit which properties you can access. If you want to get the email property for the group, you need to return it back to the DirectoryEntry object.

 PropertyValueCollection email = ((DirectoryEntry)group.GetUnderlyingObject()).Properties["mail"]; if (email.Value != null) { // Do something with email property } 
+11
source

The safest way to check a mail-enabled group is to read proxyAddresses and check for an entry starting with "smtp:". Only the test for the email field is insufficient. Extend GroupPrincipal as

 public bool IsMailEnabled { get { var proxyAddresses = ExtensionGet("proxyAddresses"); if (proxyAddresses == null) return false; if (proxyAddresses.Length == 0) return false; try { List<string> proxyAddressesStringList = proxyAddresses.Cast<string>().ToList(); if (proxyAddressesStringList.Where(x => x.StartsWith("smtp:", StringComparison.InvariantCultureIgnoreCase)).Count() > 0) return true; else return false; } catch { return false; } } } 
0
source

Source: https://habr.com/ru/post/1441882/


All Articles