Tuesday, March 31, 2009

Extracting email address from the "Assigned To" (people picker) column

I was creating a Job to send email alerts to the people whose assigned tasks are overdue. Tasks are getting created in a TaskList library by a workflow.

The job should check the DueDate column value and if it is overdue then it should send a email to the person specified in the "Assigned To" column.

The issue here is the Assigned To column value was something like "TestDomain\TestUser". I couldn't send mail using that and I required the exact email address of the "TestUser" like "Testuser@abccompany.com". I tried various approaches and the following one worked perfectly well for my scenario. [The "TestDomain" users should be imported in the SharePoint User Profiles]

try
{
SPSite site = new SPSite("
http://mysharepointsite:6666/sites/site1");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["Tasks"];
SPListItem item = list.Items[0];
string userName = list.Items[0]["Assigned To"].ToString();
SPFieldUser field = (SPFieldUser)item.Fields["Assigned To"];
SPFieldUserValue fieldValue = (SPFieldUserValue)field.GetFieldValue(userName);
MessageBox.Show(fieldValue.User.Email);
}
catch (Exception ex)
{

MessageBox.Show(ex.Message);
}

No comments: