user3848402
user3848402

Reputation: 193

Exchange web Services failed to connect

I have an exchange online service in my office 365,
and i want to send email to other person mailbox, using different method

then i found Exchange Web Services, so i tried to do the basic example:

class Program
{
    static void Main(string[] args)
    {
        //note that there no option for exchange server 2016 (my exchange online use exchange server 2016), so i use the default option  
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);   

        service.Credentials = new WebCredentials("[email protected]", "myPassword");
        service.UseDefaultCredentials = false;

        //for log purpose
        service.TraceEnabled = true; 
        service.TraceFlags = TraceFlags.All;

        service.AutodiscoverUrl("[email protected]", RedirectionUrlValidationCallback);

        EmailMessage email = new EmailMessage(service);
        email.ToRecipients.Add("[email protected]");
        email.Subject = "HelloWorld";
        email.Body = new MessageBody("This is the first email I've sent by using the EWS Managed API.");
        email.Send();

    }

    private static bool RedirectionUrlValidationCallback(string redirectionUrl)
    {
        // The default for the validation callback is to reject the URL.
        bool result = false;

        Uri redirectionUri = new Uri(redirectionUrl);

        // Validate the contents of the redirection URL. In this simple validation
        // callback, the redirection URL is considered valid if it is using HTTPS
        // to encrypt the authentication credentials. 
        if (redirectionUri.Scheme == "https")
        {
            result = true;
        }
        return result;
    }
}  

and there is exception in the AutodiscoverUrl, like this:

Microsoft.Exchange.WebServices.Data.ServiceXmlDeserializationException: 'The 
expected XML node type was XmlDeclaration, but the actual type is Element.'  

after i search a while, it said that exchange cannot find my domain, my exchange online setting is fine, i can send email, add appointment via outlook web access to other person in my mailbox

i've already change my nameserver to
ns1.bdm.microsoftonline.com
ns2.bdm.microsoftonline.com

but still doesn't fix my problem..

are there some setting that i missing?
Thx..

Upvotes: 1

Views: 1001

Answers (1)

Glen Scales
Glen Scales

Reputation: 22032

Instead of using

 service.AutodiscoverUrl("[email protected]", RedirectionUrlValidationCallback);

try

 service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");

I would suggest you set

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); 

to the highest enumeration for Office365 rather then the lowest unless you trying to support Exchange 2007.

Upvotes: 1

Related Questions