title: EWS Connection Giving Unauthorized (401) Error
body: <p>I have been working on a program that scans an exchange inbox for specific emails from a specified address. Currently the program reads the inbox, downloads the attachment, and moves the email to another folder. However, after about 15 pulls from the EWS server, the connection starts giving a 401 Unauthorized error until I restart the program. The program is setup to login via OAuth as basic auth is disabled by the system administrator. Below is the code that I am using to obtain the exchange connection and read the emails from the inbox.</p>
  <p>Exchange Connection Code:</p>
  <pre><code>public static async Task&lt;ExchangeService&gt; GetExchangeConnection()
      {
          var pcaOptions = new PublicClientApplicationOptions
          {
              ClientId = AppID,
              TenantId = TenantID,
          };
  
          var pca = PublicClientApplicationBuilder.CreateWithApplicationOptions(pcaOptions).Build();
  
          var ewsScopes = new string[] { &quot;https://outlook.office365.com/EWS.AccessAsUser.All&quot; };
  
          var securePassword = new SecureString();
          foreach (char c in Pasword)
              securePassword.AppendChar(c);
  
          try
          {
              var authResult = await pca.AcquireTokenByUsernamePassword(ewsScopes, Username, securePassword).ExecuteAsync();
  
              ExchangeService exchangeService = new ExchangeService()
              {
                  Credentials = new OAuthCredentials(authResult.AccessToken),
                  Url = new Uri(&quot;https://outlook.office365.com/ews/exchange.asmx&quot;),
              };
  
              return exchangeService;
          }
          catch
          {
              return null;
          }
      }
  </code></pre>
  <p>Email Retriever</p>
  <pre><code>public static List&lt;Email&gt; RetreiveEmails()
      {
          ExchangeService exchangeConnection = GetExchangeConnection().Result;
  
          try
          {
              List&lt;Email&gt; Emails = new List&lt;Email&gt;();
              TimeSpan ts = new TimeSpan(0, -5, 0, 0);
              DateTime date = DateTime.Now.Add(ts);
              SearchFilter.IsGreaterThanOrEqualTo EmailTimeFilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);
  
              if (exchangeConnection != null)
              {
                  FindItemsResults&lt;Item&gt; findResults = exchangeConnection.FindItems(WellKnownFolderName.Inbox, EmailTimeFilter, new ItemView(10));
  
                  foreach (Item item in findResults)
                  {
                      if (item.Subject != null)
                      {
                          EmailMessage message = EmailMessage.Bind(exchangeConnection, item.Id);
                          message.Load(new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.TextBody));
                          Emails.Add(new Email(message.DateTimeReceived, message.From.Name.ToString(), message.Subject, message.TextBody.ToString(), (message.HasAttachments) ? &quot;Yes&quot; : &quot;No&quot;, message.Id.ToString()));
                      }
                  }
              }
  
              exchangeConnection = null;
              return Emails;
          }
          catch (Exception e)
          {
              Console.WriteLine(e.ToString());
              return null;
          }
      }
  </code></pre>
  <p>The error occurs when the email retriever tries to either create the exchange connection or when requesting the emails from the folder. In either case the code will error out and give me 401 unauthorized while using credentials that work for the first dozen times and then fails after so many attempts. I have tried it with multiple different accounts and the issue persists with all of them and I have made sure that the application is authorized to access the exchange inbox. Any suggestions or help is much appreciated.</p>