public static string strLDAP = "LDAP://Test.com"; public static void GetADMails(ref List<string> list, string strLoginName) { DirectoryEntry newEntry = new DirectoryEntry(strLDAP); strLoginName = strLoginName.Substring(strLoginName.LastIndexOf('\\') + 1); DirectorySearcher newSearcher = new DirectorySearcher(newEntry, "(&(objectClass=group)(CN=" + strLoginName + "))"); SearchResult sr = newSearcher.FindOne(); if (sr != null) { foreach (string srUser in sr.GetDirectoryEntry().Properties["member"]) { DirectoryEntry tmpEntry = new DirectoryEntry("LDAP://" + srUser); if (tmpEntry.Properties["objectClass"][1].ToString() == "person") { if (string.IsNullOrEmpty(ConvertNull(tmpEntry.InvokeGet("Mail")).Trim()) || list.Contains(ConvertNull(tmpEntry.InvokeGet("Mail")).Trim())) { continue; } Console.WriteLine(tmpEntry.InvokeGet("Mail")); list.Add(ConvertNull(tmpEntry.InvokeGet("Mail")).Trim()); } else { GetADMails(ref list, tmpEntry.InvokeGet("sAMAccountName").ToString()); } } } else { newSearcher = new DirectorySearcher(newEntry, "(&(&(objectCategory=person)(objectClass=user))(cn=" + strLoginName + "))"); sr = newSearcher.FindOne(); if (sr != null) { object obj = sr.Properties["Mail"][0]; if (!(string.IsNullOrEmpty(ConvertNull(obj).Trim()) || list.Contains(ConvertNull(obj).Trim()))) { list.Add(ConvertNull(obj).Trim()); } } } } public static List<string> GetUserMailsByUserField(SPWeb web, object obj) { List<string> mailarr = new List<string>(); SPGroup group = null; if (obj == null) { return mailarr; } try { SPFieldUserValueCollection approversCollection; web.AllowUnsafeUpdates = true; approversCollection = (SPFieldUserValueCollection)obj; foreach (SPFieldUserValue spFieldUserValue in approversCollection) { if (spFieldUserValue.User == null) { //sharepoitn group try { group = web.SiteGroups[spFieldUserValue.LookupValue]; SPUserCollection users = group.Users; foreach (SPUser user in users) { if (user.ID == group.Owner.ID) { continue; } if (string.IsNullOrEmpty(ConvertNull(user.Email))) { continue; } if (mailarr.Contains(ConvertNull(user.Email).Trim())) { continue; } mailarr.Add(ConvertNull(user.Email).Trim()); } } catch { } } else { //sharepoint user or ad group try { GetADMails(ref mailarr, web.AllUsers.GetByID(spFieldUserValue.LookupId).LoginName); } catch { } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } return mailarr; }
List<string> maillist= GetUserMailsByUserField(web, item["Reader"]);