SharePoint 2013 - SPLessons

Updated user email based on user id in Sharepoint

Home > > Tutorial
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Updated user email based on user id in Sharepoint

updated user email based on user id in Sharepoint :

Description: Hi every one, Today we got a requirement that we have list and it contains user id ( it's people picker column) and some other details like city, state and country of user. The List has 1000 + records now one of my staff member need to export the list into excel and he also want's the email address of the corresponding users but we have only user id which is active directory user id. So we have added a new column named as email and run program to get the user email address by using the user id and push value into corresponding email column of each item.

Steps :

  1.  If you see the line number 13, 15 we have created SPSite, SPWeb objects.
  2. In the line number 18 we got the SPList object by passing the list name.
  3. In the line number 19 we got the all the list items in SPListItmeCollection.
  4. In the line number 22 we got the user details into SPUser object but if see we used EnsureUser method.
  5. EnsureUser is predefined method it will check whether a user exist in the current site or not.
  6. If the user does not exist in the current site it will add the user to current site.
  7. In line number 22 used a method call SPFieldLookupValue, it's predefined function.
  8. It will grab the lookup ID and lookup value. In our example lookup value means user name "Sreehari, Inukollu".
  9. In the line number 23 we push the value to email column from SPUser object.

Example Code :

[csharp] using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SharePoint; namespace InsertDataIntoSharePointList { class Program { static void Main(string[] args) { using (SPSite siteCollection = new SPSite("http://splessons")) { using (SPWeb web = siteCollection.RootWeb) { SPList lstPOCreation = web.Lists["listofspusers"]; SPListItemCollection items = lstPOCreation.GetItems(); foreach (SPListItem item in items) { SPUser to_user = web.EnsureUser(new SPFieldLookupValue(item["userid"].ToString()).LookupValue); item["email"] = to_user.Email.ToString(); item.Update(); Console.WriteLine(item["ID"]); } Console.WriteLine("****************** Please press any key to exist **************************"); Console.ReadKey(); } } } } } [/csharp]