Retrieve email id from a person or group field programatically

Requirement –  To retrieve email id of a user from a person or group field of a SharePoint list or library using C# code

Solution – Assuming that the query returns a list item collection

SPListItemCollection itemCollConfig = oConfigList.GetItems(oQuery);

if (itemCollConfig.Count > 0)
     SPFieldUser userField = (SPFieldUser)itemCollConfig.Fields.GetField("HOD");
     //strHODEmail = Convert.ToString(itemCollConfig[0]["HOD"]);
     SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(itemCollConfig[0]["HOD"].ToString());

      SPUser user = userFieldValue.User;
      strHODEmail = user.Email;

First a reference is established to the field (field name – HOD in my case), and then the user value is retrieved from the particular index for that field.

Now remember, this would work when the person or group field is configured to accept only one value at a time.

If multiple users can be selected, then the class would vary slightly and collection will be used. Assuming item reference is available

string stEmails = string.empty;
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValueCollection userFieldValueCollection = (SPFieldUserValueCollection)userField.GetFieldValue(item["Users"].ToString());
foreach (SPFieldUserValue userFieldValue in userFieldValueCollection)
strEmails = strEmails + userFieldValue.User.Email;


Next situation – When it is a people editor control on the page/web part, how to retrieve the user’s email. Below code would facilitate for the same. The people editor control here is “pplSendMail”

string strEmail = string.Empty;              
if (pplSendMail.ResolvedEntities.Count > 0)
    for (int i = 0; i < pplSendMail.ResolvedEntities.Count; i++)
        PickerEntity user = (PickerEntity)pplSendMail.ResolvedEntities[i];
        SPUser webUser = SPContext.Current.Web.EnsureUser(user.Key);
        SPFieldUserValue value = new SPFieldUserValue(SPContext.Current.Web, webUser.ID, webUser.Name);
        strEmail = strEmail + "," + webUser.Email;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s