Thursday, June 30, 2011

Sending Email Using Exchange Server 2010 EWS in Asp.Net / C#

Sending email using Exchange server EWS is breeze as compare to horrible syntaxed Web Dav ( sorry to WebDav Lovers :) ) . I worked with WebDav and many times banged my head against wall figuring out the actual issue in case of error.

EWS is web service based API of exchange server and provide very managed and readable code for sending email.

Let's start writing some code to work with ESW 2010.

First of all Add reference to Microsoft.Exchange.WebServices.dll and place Microsoft.Exchange.WebServices.xml file in your bin 

Next import following namespace.

 

using Microsoft.Exchange.WebServices;


 

public static void SendExchangeEmail(string to, string from, string subject, string body, string fileattach)

 

        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);

        service.Credentials = new NetworkCredential("ExchangeUser", "UserPassword");

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

        EmailMessage newMsg = new EmailMessage(service);

        foreach (string s in to.Split(new char[] { ',' }))

        {

            newMsg.ToRecipients.Add(s.Trim());

        }

        newMsg.Body = body;

        newMsg.Subject = subject;

        newMsg.From = from;        

 

        if (!string.IsNullOrEmpty(fileattach))

        {

            newMsg.Attachments.AddFileAttachment(fileattach);

        }

 

        newMsg.SendAndSaveCopy();  OR ( depending upon your requirment)

        newMsg.Send();

}

 

Note: Use Send method just to send and use "SendAndSave" to save a copy in your sent items

Cheers :) 

2 comments:

  1. Kindly use a proper font so that it can be readable.

    ReplyDelete
  2. this work with me like a charm , many thanks

    ReplyDelete