Get USer Names and Emails from a Sharepoint People Picker.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace GETEMAILSFROMPEOPLEPICKER
{
public static class SPFieldUserValueCollectionExtensions
{
public static IEnumerable<string> GetAllEmails(this SPFieldUserValueCollection collection, SPWeb web)
{
//System.Diagnostics.Debugger.Break();
var emails = new HashSet<string>();
foreach (var item in collection)
{
if (item.User == null)
{
try
{
// is it a SharePoint group?
var group = web.SiteGroups.GetByID(item.LookupId);
emails.AddEmailsFromSPGroup(group);
}
catch
{
// ad group
var group = web.EnsureUser(item.LookupValue);
emails.AddIfNotNull(group.Email);
}
}
else
{
emails.AddIfNotNull(item.User.Email);
}
}
return emails;
}
private static void AddEmailsFromSPGroup(this HashSet<string> emails,SPGroup group)
{
if (!string.IsNullOrEmpty(group.DistributionGroupEmail))
{
emails.Add(group.DistributionGroupEmail);
}
else
{
foreach (SPUser user in group.Users)
{
emails.AddIfNotNull(user.Email);
}
}
}
private static void AddIfNotNull(this HashSet<string> set, string s)
{
if(!string.IsNullOrEmpty(s))
{
set.Add(s);
}
}
public static IEnumerable<string> GetAllLoginNames(this SPFieldUserValueCollection collection, SPWeb web)
{
var usernames = new HashSet<string>();
foreach (var item in collection)
{
if (item.User == null)
{
try
{
// is it a SharePoint group?
var group = web.SiteGroups.GetByID(item.LookupId);
usernames.UserNamesFromSPGroup(group);
}
catch
{
// ad group
var group = web.EnsureUser(item.LookupValue);
usernames.IfNotNull(group.Name);
}
}
else
{
usernames.AddIfNotNull(item.User.Name);
}
}
return usernames;
}
private static void UserNamesFromSPGroup(this HashSet<string> usernames, SPGroup group)
{
if (!string.IsNullOrEmpty(group.DistributionGroupEmail))
{
usernames.Add(group.DistributionGroupAlias);
}
else
{
foreach (SPUser user in group.Users)
{
usernames.AddIfNotNull(user.Name);
}
}
}
private static void IfNotNull(this HashSet<string> set, string s)
{
if (!string.IsNullOrEmpty(s))
{
set.Add(s);
}
}
}
}