0

Is there a way to get the user name or the SPUser object by passing the mail address for a user, which is not already known by the site?

I know I can get the SPUser by using

SPSite.AllUsers.GetByEmail(emailAddress);

But this only works if the user is already known in the site collection. Does SharePoint (with C# Server Object Model) provide a way to search a user in the Active Directory by its mail address or do I have to use System.DirectoryServices and search in the Active Directory for myself?

Use Case:

I have a mail event receiver for a document library people can send mails to. I have some logic and at the end I want to save the attachments to this library. The Author property of the item (which is now set to SystemAccount) should be set to the person who sent the email.

  • 1
    What is the issue in ensuring the user first and then updating the Author of the item? – Nadeem Yousuf Mar 16 '15 at 15:32
  • It's an email. The only infomation I have is the user's mail address, but not the account name, which I need to ensure the user. – Fensterbank Mar 16 '15 at 16:08
  • You can get login name from email. Example, if email address is adamb@contoso.com. Then login name will be adamb. – Nadeem Yousuf Mar 16 '15 at 17:06
  • In most companies, this would work. But not in my case. The user account is something like "a1234", the mail address prename_surname@contoso.com. – Fensterbank Mar 16 '15 at 17:15
0

Please check the below code.In this way you can get the login name of the user via email address.

   using(SPWeb oWeb=new SPSite("-----URL---").RootWeb)
   {
            SPList oList = oWeb.Lists["Test"];
            foreach (SPListItem i in oList.Items)
            {
                if (i["email"] != null)
                {
                    string email = Convert.ToString(i["email"]);
                    SPWebApplication webApp = oWeb.Site.WebApplication;
                    SPPrincipalInfo principal = null;
                    principal = SPUtility.ResolvePrincipal(webApp, null, email, SPPrincipalType.User, SPPrincipalSource.Windows, true);
                    if (principal != null)
                    {
                        MessageBox.Show(principal.LoginName);

                    }
                }
            }
   }

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.