Click here to Skip to main content
15,889,931 members
Articles / Programming Languages / C#
Article

Exchange Web Services

Rate me:
Please Sign up or sign in to vote.
4.94/5 (21 votes)
6 Jun 2012CPOL6 min read 195.4K   54   9
Using Exchange Web Services.

Introduction

Microsoft Exchange Web Services (EWS) is an interface by which you can programmatically manage Exchange items such as calendar, contact, and email. With EWS, you can store or retrieve any data on your Exchange account, providing wide flexibility in managing and manipulating email data on an Exchange server for a user, a group of users, or an entire organization. EWS is a powerful tool for moving data from legacy email systems to Exchange Hosted services or Exchange Server.

What is Exchange Web Services?

Microsoft Exchange Web Services is an Application Programming Interface (API) that provides programmatic access to the information and business logic in Microsoft Exchange Server 2007 or later versions.

Prerequisites

The following are the prerequisites for programming with the EWS Managed API:

  • A computer that is running Microsoft Exchange Server 2007 Service Pack 1 (SP1) or a later version or access to Exchange Hosted Services.
  • The Microsoft .NET Framework version 3.5 or later.
  • The EWS Managed API assembly file - Microsoft.Exchange.WebServices.dll.
  • Visual Studio 2008 or higher with the Visual Web Developer and C# components.

Establishing a Connection to Exchange Server

For setting up a connection to EWS, you will need to create an ExchangeService object and connect to the correct Exchange Client Access Server (CAS) using an account with sufficient access such as an administrator. You will need both the account name and the password in order to form the connection. Below is an example of establishing this connection.

C#
ExchangeService _service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
_service.Credentials = new WebCredentials("PrimaryUserID", "PrimaryPassword");
_service.AutodiscoverUrl("user@netsoft-usa.com");

The "_service" object is now properly authenticated with the server and can be used for all subsequent interactions with the Exchange server. 

Managing Contact Items 

After establishing a connection to EWS, you can start managing your items. For retrieving your contact items from Exchange, you need to specify the Contacts folder using the WellKnownFolderName enum and how many contacts you want to retrieve from Exchange. The C# code below shows how to retrieve contact items from Exchange. It is retrieving all Contacts from Exchange; by specifying a smaller value, you can reduce the number of items returned. This can be particularly useful during searches.

C#
foreach (Contact contact in _service.FindItems(WellKnownFolderName.Contacts, new ItemView(int.MaxValue)))
{
     // do something 
}

If you choose to update or delete an item, there are a variety of options as to how the operation will take place. For example, for deleting you can specify a hard delete, and for updating you can define how conflicts should be managed.

Below is an example of how an update and delete would be invoked.

C#
contact.Update(ConflictResolutionMode.AlwaysOverwrite);
contact.Delete(DeleteMode.HardDelete);

Finally, the changes to the Contact item must be saved before the changes are reflected in the Exchange server. To save a Contact, you need to create a Contact object and populate the new Contact object’s properties with the appropriate data. For more information regarding the properties of a Contact item, please see the following link. The C# code below shows the save feature on a newly created Contact object.

C#
Contact contact = new Contact(_service);
contact.Save(WellKnownFolderName.Contacts);

Managing Calendar Items

Managing Calendar items is a little more complex than the Contact example. For Calendars, there are two distinct types: Appointments and Meetings. Both of these calendar types are accessed via the same object, and determining whether or not an item is an Appointment or a Meeting is determined by the number of attendees.

Let’s first retrieve some calendar items from Exchange. Retrieving Calendar items is just like retrieving Contact items specified in the above caption. You need to specify the type of item you wish to retrieve, and you also need to specify how many. In the code below, it is retrieving all Calendar items from Exchange. By specifying a smaller value, you can reduce the number of items returned. This can be particularly useful during searches.

C#
foreach (Appointment appointment in _service.FindItems(
         WellKnownFolderName.Calendar, new ItemView(int.MaxValue)))
{
    // do something 
}

Now you have your Calendar items. After you have performed some operations, you might want to do some actions like updating or deleting them. This is very similar to how we managed changes for the Contact items.

Below is an example of how an update and delete would be invoked.

C#
appointment.Update(ConflictResolutionMode.AlwaysOverwrite);
appointment.Delete(DeleteMode.HardDelete);

For storing the calendar items, you need to specify the SendInvitationsMode to the proper one for you in the Save method, and of course you need to populate the Appointment object's properties before calling the Save method. For further information about the Appointment object's properties, check this link.

C#
Appointment appointment = new Appointment(_service);
appointment.Save(SendInvitationsMode.SendToNone);

Managing E-Mail Items

The final item is E-Mail. Again, E-Mail managing also requires a connected service object. There are six features that all email items have in common and should be familiar to anyone who has ever used email.

  • Creating
  • Sending
  • Forwarding 
  • Replying
  • Deleting
  • Saving

All of those actions are implemented using the EmailMessage object.

Creating and sending email messages

For this feature, you need to create an EmailMessage object, populate the fields, and then send the email. The C# code below shows how to create the EmailMessage object and send the email with some populated fields. For more information about creating and sending email messages, check this link.

C#
EmailMessage message = new EmailMessage(_service);
message.Subject = "Interesting";
message.Body = "The proposition has been considered.";
message.ToRecipients.Add("user@netsoft-usa.com");
message.SendAndSaveCopy();

Forwarding email messages

For this feature, you need to create an EmailMessage object, and you need to use the Forward method of this object. For this example, I’m using the previously created EmailMessage object. The C# code below shows how to forward an email message. For more information about forwarding an email message, check this link.

C#
string messageBodyPrefix = "This message was forwarded by using the EWS Managed API";
EmailAddress[] addresses = new EmailAddress[1];
addresses[0] = new EmailAddress("user1@netsoft-usa.com");
message.Forward(messageBodyPrefix, addresses);

Replying to email messages

For this feature, you need to create an EmailMessage object, and you need to use the Reply method of this object. For this example, I’m using the previously created EmailMessage object. The C# code below shows how to reply to an email message. For more information about replying to an email message, check this link.

C#
string myReply = "This is the message body of the email reply.";
bool replyToAll = true;
message.Reply(myReply, replyToAll);

For the three features below, you need to retrieve the existing email messages from Exchange. In the case of performing these actions, you need to specify the WellKnownFolderName and the quantity of the emails you want to retrieve. In the code below, it is retrieving all EmailMessages from Exchange. By specifying a smaller value, you can reduce the number of items returned. This can be particularly useful during searches. Check these links for further information about the EmailMessage object properties and methods. The links are going to direct you to the MSDN site.

C#
foreach (EmailMessage appointment in _service.FindItems(WellKnownFolderName.Inbox, new ItemView(int.MaxValue)))
{
    // do something 
}

Updating email messages

For this feature, you need to get the "email" item in the above foreach loop, set the properties with the new data you want to replace, and then call the line of code below.

C#
email.Update(ConflictResolutionMode.AlwaysOverwrite);

Deleting email messages

For this feature, you need to get the "email" item in the above foreach loop and call the Delete method from this object as shown in the line of code below.

C#
email.Delete(DeleteMode.HardDelete);

Saving email messages

For this feature, you need to create a new EmailMessage object, populate the values with proper data, and then call the save method from the created object. You can see these operations in the code example below.

C#
EmailMessage email = new EmailMessage(_service);
email.Save();

History 

First release, June 6th, 2012. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionProblem when reading email Pin
errors_8110-Sep-15 0:23
errors_8110-Sep-15 0:23 
QuestionEWS is not working for me and it is giving UnAuthorized User Pin
Subhash M.Tech AI22-Sep-14 18:32
Subhash M.Tech AI22-Sep-14 18:32 
QuestionAdding an "all day event" Pin
Member 1031856614-Oct-13 7:22
Member 1031856614-Oct-13 7:22 
QuestionAre you able to use EWS to set a forwarding email? Pin
Michael D Bray13-Jun-13 8:16
Michael D Bray13-Jun-13 8:16 
Title says it all... I want to programmatically set a forwarding email on my account. Can EWS do that?
Questionretrive appoimntment details from calender using C# with exchange server Pin
puvanar8-Jan-13 0:43
puvanar8-Jan-13 0:43 
QuestionQuestion about calendar meeting . Pin
Member 81661013-Nov-12 2:25
Member 81661013-Nov-12 2:25 
Generalnice article Pin
acarpio197524-Sep-12 14:33
acarpio197524-Sep-12 14:33 
QuestionJava and .NET EWS Pin
Ziko9930-Jul-12 1:52
Ziko9930-Jul-12 1:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.