Search code examples
c#exchange-serverexchangewebservices

How to access Outlook Exchange Server with Username and Password from Windows Login?


I am creating a "simple" VSTO (Outlook plugin) in WinForms using VS19 for my company, which will scan all folders for Social Security Numbers and list the email-item in a listView, so the user can delete the mails.

I am using the EWS Managed API client: https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/get-started-with-ews-managed-api-client-applications?redirectedfrom=MSDN

I have implemented the above fine but the problem is that I don't know how to access the Exchange Server properly. In the examples provided in the link, the username and password are hardcoded and since this is an application released to several different users I would like to access the exchange server with the windows login (This is the same login in my company).

using Microsoft.Exchange.WebServices.Data;

// Setup how to download emails from the exchange server
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
service.Credentials = new WebCredentials("test.tester", "test123","domaintest");
service.AutodiscoverUrl("[email protected]");


// Add all the mails from exchange server (inbox) to a list
bool more = true;
ItemView view = new ItemView(int.MaxValue, 0, OffsetBasePoint.Beginning);
view.PropertySet = PropertySet.IdOnly;
FindItemsResults<Item> findResults;
List<EmailMessage> emails = new List<EmailMessage>();
while (more)
{
     findResults = service.FindItems(WellKnownFolderName.Inbox, view);
     foreach (var item in findResults.Items)
        {
        emails.Add((EmailMessage)item);
        }
        more = findResults.MoreAvailable;
        if (more)
        {
            view.Offset += 1000;
        }
}

When I hardcode my information in the code above everything works fine and I can access the inbox folder and make a list with the email messages

After searching for several hours without results I hope you will be able to help me.


Solution

  • If you are targeting an on-premises Exchange server and your user credential is domain joined:

    service.UseDefaultCredentials = true;
    

    Domain-joined clients that target an on-premises Exchange server can use the default credentials of the user who is logged on, assuming the credentials are associated with a mailbox. Add the following code after the instantiation of the ExchangeService object.

    // Setup how to download emails from the exchange server
    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
    service.UseDefaultCredentials = true;
    service.AutodiscoverUrl("[email protected]");
    

    But if you are targeting an Exchange Online or Office 365 Developer Site mailbox, you have to pass explicit credentials.