Search code examples
c#.netexchangewebservices

I need to get emails with help of EWS in C#


Here is my code:

using System;
using System.Net;
using MailListClient.MailListServiceReference;
using Microsoft.Exchange.WebServices.Autodiscover;
using Microsoft.Exchange.WebServices.Data;

namespace MailListClient
{
   class Program
   {
       static void Main(string[] args)
       {
           var service = GetBinding();

           ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;

           try
           {
               FindItemsResults<Item> findResults = service.FindItems(
                   WellKnownFolderName.Inbox,
                   new ItemView(10));

               foreach (Item item in findResults.Items)
                   Console.WriteLine(item.Id);
           }
           catch (Exception ex)
           {
               Console.WriteLine("Error: " + ex.Message);
               Console.ReadLine();
           }
       }

       static ExchangeService GetBinding()
       {
           ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
           service.Credentials = new WebCredentials("zxzxzxzxzx@email.com", "password");
           try
           {
               service.Url = new Uri("https://email.com/AutoDiscover/AutoDiscover.xml");
           }
           catch (AutodiscoverRemoteException ex)
           {
               Console.WriteLine("Exception thrown: " + ex.Error.Message);
           }
           return service;
       }
   }
}

But I get Exception: The request failed. The remote server returned an error: (404) Not Found. What is the problem?


Solution

  • Your URL may be wrong. Here is the URL format I am using in code which is definitely working in a few applications (2007 and 2010):

    https://[fully qualified domain name]/EWS/Exchange.asmx
    

    The rest of your code looks correct at a cursory level.