Search code examples
c#authenticationexchange-serverexchangewebservices

EWS reduce mailbox connection time


I have a program for reading incoming mail outlook (exchange server 2016) the program runs in the task scheduler windows using account "system" but at the connection step the program waits a few minutes. if the program starts using a domain account, then the connection is made without expectations. I do not want to change the settings in the task scheduler windows. I think that the problem is in the connection timeout, how to reduce connection time and start searching for the mailbox after domain authorization?

I use this when connecting :

string url = "Url";
string UserLogin = "UserLogin";
string UserPassword = "UserPassword";
string UserDomain = "UserDomain";
string UserEmail = "UserEmail";

ExchangeService ews = new ExchangeService();
UserPrincipal userP = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, UserDomain, UserLogin, UserPassword), Environment.UserName);
ews.Credentials = new WebCredentials(UserLogin, UserPassword, UserDomain);
Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverRedirectionUrlValidationCallback RedirectionUrlValidationCallback = null;
ews.AutodiscoverUrl(UserEmail, RedirectionUrlValidationCallback);

Folder inbox = Folder.Bind(ews, WellKnownFolderName.Inbox);
PropertySet propSet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Body);


Solution

  • I'd start with

    UserPrincipal userP = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, UserDomain, UserLogin, UserPassword), Environment.UserName);
    

    Its not necessary for the EWS code and I can't see you using the object it returns. You could use a StopWatch https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch?view=netframework-4.8 and time each line of you code and write that to log file to see where the delay it.

    Other things you could do to test (if it makes a difference) is hard code the EWS endpoint and remove the Autodiscover operation (by default this does several DNS and LDAP queries to work out the endpoint so try)

            string url = "Url";
            string UserLogin = "UserLogin";
            string UserPassword = "UserPassword";
            string UserDomain = "UserDomain";
            string UserEmail = "UserEmail";
            string EwsEndpoint = "https://yourserver.youneedtodefine.com/EWS/Exchange.asmx";
    
            ExchangeService ews = new ExchangeService();
            ews.Credentials = new WebCredentials(UserLogin, UserPassword, UserDomain);
            ews.Url = new Uri(EwsEndpoint);
    
            Folder inbox = Folder.Bind(ews, WellKnownFolderName.Inbox);
            PropertySet propSet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Body);