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.

1
  • Do you want to read or update full name?
    – Jinxed
    Commented Nov 17, 2014 at 12:10

2 Answers 2

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;
}
6
  • 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 Commented Nov 17, 2014 at 12:28
  • Weird, it should work.. Can you try (SPFieldUserValue)oListItem["Author"] instead of oListItem["Author"] as SPFieldUserValue ? Commented Nov 17, 2014 at 12:33
  • Could it be because I am using this code in timer job? Commented Nov 17, 2014 at 12:35
  • When using second code you posted, getting error "Unable to cast object of type 'System.String' to type 'Microsoft.SharePoint.SPFieldUserValue'." Commented Nov 17, 2014 at 12:38
  • @FrankMartin try the updated code in answer Commented Nov 17, 2014 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 and acknowledge you have read our privacy policy.

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