the remote certificate is invalid according to the validation procedure.

Problem statement – While sending email using SMTP client using C# code, the following error comes up the remote certificate is invalid according to the validation procedure.

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel

Solution – Add the code before calling smtpClient.Send(mail)

//Add following namespaces
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

smtpClient.EnableSsl = true;

ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };

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;