0

I want to get email of users who are uploading documents in a library. You know there is a field called "Created By" which contain full name, so I want to read that name and then find that user's email.

Is there a way to do it without querying Active Directory?

There is another method (given below) but for it to work you need to know userid of user.

SPSite oSiteCollection = SPContext.Current.Site;
using (SPWeb oWebsite = oSiteCollection.AllWebs["Website_Name"])
{
    SPUser oUser = oWebsite.AllUsers["User_Name"];

    oUser.Email = " E-mail_Address";

    oUser.Update();
}

What I have is full name only which is saved in "Created By" field of any library.

  • Do you want to read or update full name? – Harshini Hegde Nov 17 '14 at 12:10
2

Try the below code snippet

SPWeb oWebsite = SPContext.Current.Web;

SPDocumentLibrary oDocumentLibrary = (SPDocumentLibrary)oWebsite.Lists["DocLib_Name"];

SPListItemCollection collListItems = oDocumentLibrary.Items;

foreach (SPListItem oListItem in collListItems)
{
   var strAuthor = oListItem["Author"].ToString();
   var author = new SPFieldUserValue(web, strAuthor);
   SPUser user = author.User;
   var email = user.Email;
}
  • The code oListItem["Author"] as SPFieldUserValue is returning null even though if I see the value in Immediate Window then it displays users name. But when code is run the the variable "author" becomes null – Frank Martin Nov 17 '14 at 12:28
  • Weird, it should work.. Can you try (SPFieldUserValue)oListItem["Author"] instead of oListItem["Author"] as SPFieldUserValue ? – Arsalan Adam Khatri Nov 17 '14 at 12:33
  • Could it be because I am using this code in timer job? – Frank Martin Nov 17 '14 at 12:35
  • When using second code you posted, getting error "Unable to cast object of type 'System.String' to type 'Microsoft.SharePoint.SPFieldUserValue'." – Frank Martin Nov 17 '14 at 12:38
  • @FrankMartin try the updated code in answer – Arsalan Adam Khatri Nov 17 '14 at 13:09
1

Fixed it by using the following code:

SPFieldUserValueCollection users = new SPFieldUserValueCollection(web, item["Author"].ToString());

    foreach (SPFieldUserValue userDetail in users)
    {
        SPUser user = userDetail.User;
        string email = userDetail.Email;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.