Send email to a user, getting it from a ‘Person or Group’ field in a List
First, we have to read from “Person or Group” field.
It could be a “Person or Group” field that allows one user to be selected.
It could be a “Person or Group” field that allows multiple users to be selected.
If its a single user, get user, get his email address, send him email.
If there are multiple users, get each of them one by one, get their email addresses, send them emails.
Do not copy/paste the code; and if you do, look for the typos
using System.Net.Mail;
using (SPSite mySite = new SPSite("http://server/site"))
{
using(SPWeb myWeb = mySite.OpenWeb())
{
SPList myList = myWeb.Lists["myListNameHere"];
SPFieldCollection allMyListFields = myList.Fields;
foreach(SPListItem myItem in myList.Items) //go through all the items
{
foreach (SPField myField in allMyListFields) //go through all the fields
{
if (myField.GetType() == typeof(SPFieldUser)) //check if the field is Person or Group field i.e. SPFieldUser
{
Type fieldType = myField.GetFieldValue(myItem[myField].ToString()).GetType();
if (fieldType == typeof(SPFieldUserValueCollection)) //check if the field allows multiple selection of users
{
string emailToFieldValues = myItem[myField].ToString();
SPFieldUserValueCollection emailToUsers = new SPFieldUserValueCollection(myItem.Web, emailToFieldValues.ToString());
foreach (SPFieldUserValue emailUser in emailToUsers)
{
SPUser emailThisUser = emailUser.User;
string emailAddress = emailThisUser.Email.ToString();
SPUtility.SendEmail(myWeb, true, true, emailAddress, emailSubject, emailBody);
}
}
else
{
SPFieldUserValue emailToFieldValue = (SPFieldUserValue)myField.GetFieldValue(myItem[myField].ToString());
SPUser emailToUser = emailToFieldValue.User;
string emailToAddress = emailToUser.Email.ToString();
SPUtility.SendEmail(myWeb, true, true, emailToAddress, emailSubject, emailBody);
}
} //if1
} //foreach2
} //foreach1
} //SPWeb
} //SPSite
Hope this helps–



