read email using exchange web services
Asked Answered
H

6

7

This is my scenario: I have to read email from exchange 2010 sp2 accounts. I have to use Exchange Web Services, POP3 and IMAP are blocked. I have to test my app in an environment where people can access their accounts through a web browser only in the intranet. I can't debug my app directly to this intranet. I have this snippet to access an account:

private void Dowork()
{
    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);

    string dominio = "domain";
    string usuario = "user";
    string password = "password";

    service.Credentials = new NetworkCredential(usuario, password, dominio);

    string url = usuario + "@" + dominio + ".com";

    service.AutodiscoverUrl(url, RedirectionUrlValidationCallback);
    //service.AutodiscoverUrl(url);

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

    string content = string.Empty;

    foreach (Item item in findResults.Items)
    {
        EmailMessage email = EmailMessage.Bind(service, item.Id);
        email.Load();

        content += item.Subject + "\n";
        content += email.From.Address + "\n";
        content += email.Body + "\n\n";

        //Console.WriteLine(item.Subject);
        //Console.WriteLine(email.From.Address);
        //Console.WriteLine(email.Body);
    }

    string result = content;
}

// Create the callback to validate the redirection URL.
static bool RedirectionUrlValidationCallback(String redirectionUrl)
{
    // Perform validation.
    return (redirectionUrl == "https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml");
}

If I use this line:

service.AutodiscoverUrl(url);

I get this error:

"Autodiscover blocked a potentially insecure redirection to https://autodiscover.colpatria.com/autodiscover/autodiscover.xml. To allow Autodiscover to follow the redirection, use the AutodiscoverUrl(string, AutodiscoverRedirectionUrlValidationCallback) overload."

So the method RedirectionUrlValidationCallback was implemented, I'm not sure if the url is right. The fact is I'm getting this error:

"The Autodiscover service couldn't be located".

Is possible that Autodiscover is not configured properly?? I'm not the exchange administrator, how can I know if autodiscover works?? I need arguments to tell exchange administrators this feature must be configured. Thanks for any help.

Heisel answered 13/7, 2012 at 19:39 Comment(2)
I'm sure you have found a way by now as this question is a year old, just want to add that using calling AutoDiscoverUrl is not the only way to connect with EWS. Instead setting the url directly yourself could be a viable alternative. Example: service.Url = new URI("https://your_exchange_server/EWS/Exchange.asmx");Urchin
Hardcoding the service.Url is not the right way !! We use Autodiscover for a purpose. It allows us not to worry if user is on-premise or Office365. The EWS endpoint Url will be set as service.Url automatically.Ruthannruthanne
H
4

This is a old post I thought I'd put in a full example solution for the error reported. Simply replace service.AutodiscoverUrl("[email protected]"); with System.Uri("https://mail.somedomain.org/ews/Exchange.asmx");

Here's the full block of code

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
                service.Credentials = new WebCredentials("someuser", "somepassword");
                //service.AutodiscoverUrl("[email protected]");
                service.Url = new System.Uri("https://mail.somedomain.org/ews/Exchange.asmx");
Hovis answered 1/2, 2016 at 16:45 Comment(0)
U
2

Somehow you need to log the result of what redirectionUrl is. You will get this error when your redirectionUrl doesn't match the URI you've specified (i.e. your autodiscover validation callback returns FALSE). Certainly the redirectionUrl URI is not what you think it is. If you are using SSL - you need to handle the redirect validation callback.

Since you cannot debug the application, perhaps you could send an email to yourself, log to a shared DB or file, or perhaps use the app event log (throwing an application exception).

Note: The first error does tell you the autodiscover URI is https://autodiscover.colpatria.com/autodiscover/autodiscover.xml. Should this replace the existing string https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml?

Also see related SO post regarding Exchange Autodiscovery and Validating a Potentially Unsafe Redirection URL on MSDN.

Unscratched answered 18/7, 2012 at 18:41 Comment(0)
B
2

Having run into similar issues recently and working to resolve them I discovered a utility that was/is very helpful in troubleshooting: EWS Editor It may not solve your problems but can be used to iterate over different configuration combinations very quickly which will hopefully shed some light on your issues.

I used this app when Working with a client to establish Autodiscover and Service URL connections to test and prod Exchange servers. It was handy not only for me but the client's IT staff as well. They downloaded and used the utility to test and verify their settings.

From http://ewseditor.codeplex.com :

Project description

EWSEditor has three goals:

  1. Demonstrate the Exchange Web Services Managed API functionality and simplicity to developers through its source code.

  2. Demonstrate the Exchange Web Services SOAP traffic used to perform actions initiated through an explorer user interface.

  3. Assist non-developers in debugging and understanding Exchange stores by exploring items, folders, and their properties in depth

Bernardobernarr answered 14/6, 2013 at 17:5 Comment(0)
T
0

Try service.TraceEnabled = true;

WFM. In my case I needed to set up SSL/TLS by installing a certificate from the Exchange Server onto the client machine. I was led to this solution from the output of the trace.

Tunicle answered 24/2, 2016 at 23:46 Comment(0)
R
0

This works like a charm to me:

   var exchange = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
   var username = Settings.EmailUserName;
   var password = Settings.EmailPassword;
   var domain = Settings.EmailDomain;
   var email = Settings.Email;
   exchange.Credentials = new WebCredentials(email, password);
   exchange.AutodiscoverUrl(email, RedirectionCallback);

and the RedirectionCallback is:

 static bool RedirectionCallback(string url)
        {
            // Return true if the URL is an HTTPS URL.
            return url.ToLower().StartsWith("https://");
        }

heres is the link: https://msdn.microsoft.com/en-us/library/office/dd635285(v=exchg.80).aspx

Regards!

Roanna answered 11/12, 2017 at 14:50 Comment(0)
R
0

When you used AutodiscoverUrl() with RedirectionUrlValidationCallback, here is a sample code:

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.PreAuthenticate = true;
service.Credentials = new WebCredentials("my_username","my_password"); //use WebCredentials instead of NetworkCredential
service.AutodiscoverUrl(userEmailAddress, RedirectionCallback);

And RedirectionCallback method be like:

        static bool RedirectionCallback(string url)
        {
            bool redirectionValidated = false;
            Uri redirectionUri = new Uri(url);

//There are two ways of implementing a RedirectionCallback scheme

// Way 1: Return true if the URL is an HTTPS URL.
            //return url.ToLower().StartsWith("https://");
            if (redirectionUri.Scheme == "https")
                redirectionValidated = true;

//Way 2: check if url is autodiscovery url
            if (url.Equals(
                "https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml"))
                redirectionValidated = true;

            return redirectionValidated;
        }

PS: Take care of proxies disallowing Autodiscovery service. In my case, this code everytime returned "The Autodiscovery service cannot be located" error, but the root cause was 403 Forbidden on Autodiscovery call. It did work after proxy settings.

Ruthannruthanne answered 3/5, 2019 at 10:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.