Challenge
On a recent project, I needed a way to build a list of emails for a given SPListItem. Considering most of you just want the code, here it is:
Solution
public ListGetEmailsForUsersAssociated(SPListItem item) { //list for emails List emails = new List (); //omitted for brevity... SPSecurity.RunWithElevatedPrivileges(delegate() { try { using (SPSite ospSite = new SPSite(siteUrl)) { using (SPWeb currentWeb = ospSite.OpenWeb()) { SPListItem p_Item = currentWeb.GetListItem(dataSiteName + "/" + itemUrl); SPRoleAssignmentCollection usersOrGroups = p_Item.RoleAssignments; foreach (SPRoleAssignment userOrGroup in usersOrGroups) { if (userOrGroup.Member.GetType().ToString() == "Microsoft.SharePoint.SPUser") { //Get user and add to email list SPUser user = (SPUser)userOrGroup.Member; if (!String.IsNullOrEmpty(user.Email)) if (!emails.Contains(user.Email)) emails.Add(user.Email); } else if (userOrGroup.Member.GetType().ToString() == "Microsoft.SharePoint.SPGroup") { String groupName = userOrGroup.Member.ToString(); SPGroup group = currentWeb.SiteGroups[groupName]; SPUserCollection users = group.Users; foreach (SPUser user in users) { if (!String.IsNullOrEmpty(user.Email)) if (!emails.Contains(user.Email)) emails.Add(user.Email); } } } } } } catch (Exception e) { throw e; } }); return emails;
Additionally, if you would like to remove duplicate emails, you can do so with some quick LINQ:
string bcc = emails.Distinct().ToList().Aggregate((First, Second) => First + ";" + Second);Share and Enjoy:











No related posts.