开发者

Get current user's email address in .NET [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post.

开发者_如何学JAVA

Closed 2 years ago.

Improve this question

I would like to know the email address of the user (assuming she's in a typical Windows office network). This is in a C# application. Perhaps something to the effect of

CurrentUser.EmailAddress; 


Reference System.DirectoryServices.AccountManagement, then

using System.DirectoryServices.AccountManagement;
return UserPrincipal.Current.EmailAddress;

See .NET docs UserPrincipal.Current and UserPrincipal.EmailAddress.


Or with a timeout:

var task = Task.Run(() => UserPrincipal.Current.EmailAddress);
if (task.Wait(TimeSpan.FromSeconds(1)))
    return task.Result;
    


If you're behind a Windows domain, you could always grab their email address out of Active Directory.

See Javier G. Lozano's example in his tutorial, "Querying Active Directory for User Emails".


// Simply by using UserPrincipal
// Include the namespace - System.DirectoryServices

using DS = System.DirectoryServices;
string CurrUsrEMail = string.Empty;
CurrUsrEMail = DS.AccountManagement.UserPrincipal.Current.EmailAddress;


I didn't want to use the Active Directory option and the other, most selected answer, did not work for me oddly enough.

I searched my code bank and found this which worked fine and with quick response:

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "[domain]",  dc=xx,dc=yyy"))
{
    UserPrincipal cp = UserPrincipal.FindByIdentity(ctx, Environment.UserName);
    userEmail = cp.EmailAddress;
}


No doubt many are fine using Directory Services (LDAP etc.), however for those not able (or willing) this might work as an alternative.

PM> Install-Package Microsoft.Office.Interop.Outlook -Version 15.0.4797.1003

using MSOutlook = Microsoft.Office.Interop.Outlook;
using System.Runtime.InteropServices;

...

private async Task<string> GetCurrentUserEmailAsync()
{
    var value = string.Empty;
    MSOutlook.Application outlook = new MSOutlook.Application();
    await Task.Delay(3000);
    MSOutlook.AddressEntry addrEntry =
        outlook.Session.CurrentUser.AddressEntry;
    if (addrEntry.Type == "EX")
    {
        MSOutlook.ExchangeUser currentUser =
            outlook.Session.CurrentUser.
            AddressEntry.GetExchangeUser();
        if (currentUser != null)
        {
            value = currentUser.PrimarySmtpAddress;
        }
        Marshal.ReleaseComObject(currentUser);
    }
    Marshal.ReleaseComObject(addrEntry);
    Marshal.ReleaseComObject(outlook);
    return value;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜