Send E-mail through Microsoft Exchange using .NET

Send E-mail through Microsoft Exchange using .NET

Recently I needed to send an e-mail using Microsoft Exchange Server from an ASP .NET Web App.

My first attempt involved using the classes in the System.Net.Mail namespace however I quickly realised this wasn’t the way to be going about it as I had very little luck getting a connection to the server.

After a while spent with Google I realised that there were some web services which could be used to perform tasks, these were called Exchange Web Services (EWS) and thankfully Microsoft provide a managed API which can be used to connect to and use them!

I thought this was exactly what I needed to I was surprised to be informed that the API was already installed when I tried to run the installer. I can only imagine that this was because I had Office already installed or because I installed Visual Studio with all the optional components.

In any case I eventually found the 32-bit version at the following path:

C:\Program Files (x86)\Microsoft\Exchange\Web Services\2.0

Below is a simple example of how to use the EWS Managed API to connect to an exchange server and send an e-mail message.

var service = new ExchangeService();
service.Url = new Uri("https://yourexchangeserver/ews/exchange.asmx");
service.Credentials = new WebCredentials("yourusername", "yourpassword");

EmailMessage message = new EmailMessage(service);
message.ToRecipients.Add("test@test.com");
message.From = "test@test.com";
message.Subject = "Your Subject";
message.Body = "Your Message!";

message.Send();

I hope this saves someone some time when hunting for a quick solution!