Wednesday, October 24, 2012

How to get client machine Outlook username using Asp.Net ?

If we want to get server Outlook user name then it is easy to get because for this we can simply use “Microsoft.Office.Interop.Outlook” Namespace, and after creating the object of “Microsoft.Office.Interop.Outlook.Application“ Class we can get server Outlook user name.

But we face the problem when we want to get Client side (Client machine) Outlook user name, because “Microsoft.Office.Interop.Outlook” Namespace targets to server side machine. In this article, I am explaining - How to get client machine Outlook username?

As we want to get client machine Outlook user name so we have to write code which will target to client machine, so I have used JavaScript for this. Using JavaScript I am dealing with ActiveX object so it is must that our browser should allow ActiveX control.

For this we need to set following setting for our browser-
1. Open Internet Explorer
2. Go to "Internet Options Settings"
3. Open "Security Tab"
4. Mark as enable for "Initialize and script ActiveX controls option"

Like this-

Internet options

This setting will help to deal with client machine Outlook object.

Now use following code -

 protected void btnGetOutlookUser_Click(object sender, EventArgs e)
       string script = " <script  type ='text/javascript' >";
       script = script + " try {";
       script = script + "obj = GetObject('', 'Outlook.Application');";
       script = script + "alert(obj.Session.CurrentUser.Address);";
       script = script + "}";
       script = script + "catch (e) {";
       script = script + "alert(e.Message + ' Not Supported');";
       script = script + "}; ";
       script = script + "</script>";
       ClientScript .RegisterClientScriptBlock(this.GetType(),"key", script);

In this code, I have used JavaScript code. Using GetObject() method I am creating object for Outlook Application that will target to client machine Outlook object.

obj = GetObject('', 'Outlook.Application');

Now to get the Client Session, I am using Session property of this object (obj), using this Session property we can deal with all options of Outlook for client machine.
Like I have used, to get user name, I have used this code-


Here Address will point to Outlook user name of Client machine, for different client machine this line of code will give different user name based on outlook user name.

Output will be like this-

Outlook Username

Note- This example will work only with Internet Explorer.


No comments:

Post a Comment