SharePoint: Getting Email Address from Username

Just a quick post – I have encountered some convoluted ways of getting somebody’s email address when you only know there login name. The best ways to get this information are typically as follows:

When the user has permissions on the SharePoint site where your code is running from, use the following:

Using (SPSite site = new SPSite(“http://url/of/site“))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPUser person = web.AllUsers[“ct\loginname”];
        string email = person.email;
        string displayName = person.name;       

        // etc…
    }
}

When the user does not have permission on the SharePoint site, but belongs to the domain that your server running code is joined to:

DirectorySearcher searcher = new DirectorySearcher();
string username = “nnow”;
searcher.Filter = String.Format(“(&(objectClass=user)(cn={0}*))”, username); 
SearchResult result = searcher.FindOne();
if (result != null)
{
    string email = result.Properties[“mail”][0].ToString();
    string displayname = result.Properties[“displayname”][0].ToString();
}

Note that you need to reference the System.DirectoryServices namespace.

You May Also Like

About the Author: rnowik

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.