Pull users and groups from a SP list that allows multiple users and groups.

This is a follow up post from a previous post :

http://surfpointtech.com/2011/09/12/how-to-pull-the-email-addresses-from-a-sharepoint-user-field-allow-multiple-users/

When examining a User field on a SharePoint list, you need to see whether the list setting allows for multiple users as well as both Users and Groups.

The key to pulling both the groups and the users is to be able to test for a group as opposed to a user object.  In this case, I found that the fieldUser.User object is null for groups, but not for Users.  So, as you iterate through the fieldUser objects in the SPFieldUserValueCollection, you’ll find a group when the fieldUser is not null, but the fieldUser.User object is null.  That way, you know you have a SPGroup at that point, and can loop through the users in the group.

After that, you do the normal adding of each fieldUser.User.Email

I can vouch that this works for SPGroups, but have not tested with any AD groups at this point.

//Mail.To based on Users or Groups, allow multiple

SPFieldUser UsersColumn = (SPFieldUser)workflowProperties.Item.Fields.GetField(“Pending Response From”);

SPFieldUserValueCollection Users = (SPFieldUserValueCollection)UsersColumn.GetFieldValue(workflowProperties.Item[“Pending Response From”].ToString());

foreach (SPFieldUserValue fieldUser in Users)

{

//User object is null for groups, so if User is null, loop to add each user in the group.if (fieldUser.User == null)

{

SPGroup group = this.workflowProperties.Item.Web.SiteGroups[fieldUser.LookupValue];foreach (SPUser user in group.Users)

{

mail.To.Add(user.Email);

}

}

//else

{

mail.To.Add(fieldUser.User.Email);

}

//

}

//