Search code examples
asp.netemailsendmailexchange-serverexchangewebservices

Cannot send email to recipients outside local network on Exchange server with ASP.net


I am developing an ASP.NET application using Web Forms and I'm stumbling on the (I think trivial) problem of sending an email from a Microsoft Exchange Server account.

I use the ExchangeService class (with the Microsoft EWS API) and the AutodiscoverUrl function to connect to the Exchange server.

This is my code:

protected void Button2_Click(object sender, EventArgs e)
{
   string from = "myemail@myexchangeserver.com";
   string to = "recipient@email.com";

   ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
   service.AutodiscoverUrl(from);

   EmailMessage message = new EmailMessage(service);
   message.Subject = "Email Subject";
   message.Body = TextBoxMessage.Text;
   message.ToRecipients.Add(to);
   message.Save();

   message.SendAndSaveCopy();
}

The problem is that I can only send emails to local email addresses i.e. from and to the Exchange server (only addresses from my company). Sending to an "external" emails such as gmail does not work, although the SendAndSaveCopy call does not throw any exception.

I should mention that this only works from my development server inside the company´s local network. If I disconnect from the local network, I can't connect to the Exchange server anymore and an exception is thrown.

What am I doing wrong?


Solution

  • It turned out that my server does not accept AutodiscoverUrl and I had to manually set the credentialsto the emailaccount with service.Credentials = new WebCredentials("userName", "password", "Domain");

    Thank you for your comments, it really helped!