Click here to Skip to main content
6,292,426 members and growing! (10,173 online)
Email Password   helpLost your password?
Enterprise Systems » Microsoft Exchange » General     Intermediate License: The Code Project Open License (CPOL)

Programming With Exchange Server 2007 (EWS) - Part 1

By Brij

This article is the first part of the series on EWS which explores Exchange Web Services
C# 2.0.NET 2.0, ASP.NET, Architect, Dev
Posted:20 Aug 2008
Updated:28 Aug 2008
Views:30,205
Bookmarked:40 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
17 votes for this article.
Popularity: 4.87 Rating: 3.96 out of 5
2 votes, 11.8%
1
1 vote, 5.9%
2
3 votes, 17.6%
3
1 vote, 5.9%
4
10 votes, 58.8%
5

Introduction

Recently I worked on a custom MailClient project. In that, we used EWS API provided by Exchange Server 2007 which is fairly new. During development, we faced many problems. On the Internet, you will get a lot of results but they are really scattered and some of them are missing. Here I want to share my knowledge with all of you and try to provide all the required information and sample code in this series. In every part, I'll take one functionality and try to explore that. Any suggestion will be highly appreciated.

What Is Exchange Server?

Exchange Server is a messaging system that includes Mail Server, e-mail client and GroupWare application. Exchange Server is generally used with Microsoft Outlook and tightly integrated with Active Directory and Instant Messenger.

Messaging System comprises creation, storage, maintenance of different kinds of messages like email, voice mail, fax, images, etc.

Exchange Server API's History

exchange11.JPG

What is Exchange Web Services

EWS (Exchange Web Services) is an Application Programming Interface which can be used by different developers to communicate with Microsoft Exchange Server 2007.

This API is exposed as SOAP (Simple object Access Protocol)- based Web-service, which means a requester must send their request in an XML form using SOAP to EWS contained in an HTTP POST request. EWS itself responds in the same manner using SOAP and XML messages in the HTTP response object. EWS is exposed on a Exchange Client Access Server (CAS) through an ASP.NET 2.0 Web service. This can be represented pictorially as follows:

Exchange22.JPG
Client talking SOAP + XML to EWS

Special Features

  • Efficient access to Outlook PIM objects
  • Notifications and events
  • Synchronization
  • Availability service
  • Autodiscover service
  • E-mail Lifecycle
  • OWA WebParts

How to Use EWS

Most Web services publish a “Contract” of sorts that tell those on the outside what the service can do and how to communicate with it. EWS exposes this contract as a standard Web Services Description Languages (WSDL) document named services.wsdl which resides in the same directory as Web service. One can look into it.

To use it “Add a Web Reference to your project”. It may ask you to supply your credentials, so go ahead if prompted.

Note: Certificate Issues - depending on the nature of the certificate that the Exchange CAS provides to Visual Studio, It might complain that the certificate is untrusted and disable the Add Reference button, so you need to install this certificate.

Now you are ready to use the EWS in your application.

Here, I will take one method exposed by EWS and try to explore it.

Using the Code

How to Send a Mail - Normal Mail

The sample code is like this:

public void SendMessage(
string subject,
string body,
string toEmailAddress)
{
 // Set the version, credentials, and the Client Access server on ExchangeServiceBinding.
    ExchangeServiceBinding esb = new ExchangeServiceBinding();
    esb.Credentials = new NetworkCredential("user2", "password", "domain");
    esb.Url = "https://www.example.com/ews/exchange.asmx";

// Create a CreateItem request object
CreateItemType request = new CreateItemType();

// Setup the request:
// Indicate that we only want to send the message. No copy will be saved.
request.MessageDisposition = MessageDispositionType.SendOnly;
request.MessageDispositionSpecified = true;

// Create a message object and set its properties
MessageType message = new MessageType();
message.Subject = subject;
message.Body = new BodyType();
message.Body.BodyType1 = BodyTypeType.Text;
message.Body.Value = body;
message.ToRecipients = new EmailAddressType[1];
message.ToRecipients[0] = new EmailAddressType();
message.ToRecipients[0].EmailAddress = toEmailAddress;
message.ToRecipients[0].RoutingType = "SMTP"; 

//There are some more properties in MessageType object 
//you can set all according to your requirement
// Construct the array of items to send
request.Items = new NonEmptyArrayOfAllItemsType();
request.Items.Items = new ItemType[1];
request.Items.Items[0] = message;

// Call the CreateItem EWS method.
CreateItemResponseType response = esb.CreateItem(request);
this.ThrowOnError("SendMessage", response.ResponseMessages.Items[0]);
}

How to Send a Mail with Attachment

To send mail with attachment:

  1. Create a MessageType object using CreateItem
  2. Add the attachments using CreateItem
  3. Send the message using SendItem

Creating a messageType Object using CreateItem

public ItemIdType CreateMessage(
string subject,
string body,
string toEmailAddress)
{
 // Set the version, credentials, and the Client Access server on ExchangeServiceBinding.
    ExchangeServiceBinding esb = new ExchangeServiceBinding();
    esb.Credentials = new NetworkCredential("user2", "password", "domain");
    esb.Url = https://www.example.com/ews/exchange.asmx;

// Create a CreateItem request object
CreateItemType request = new CreateItemType();

// Setup the request:
// Indicate that we only want to send the message. No copy will be saved.
request.MessageDisposition = MessageDispositionType.SaveOnly;
request.MessageDispositionSpecified = true;

// Create a message object and set its properties
MessageType message = new MessageType();
message.Subject = subject;
message.Body = new BodyType();
message.Body.BodyType1 = BodyTypeType.Text;
message.Body.Value = body;

message.ToRecipients = new EmailAddressType[1];
message.ToRecipients[0] = new EmailAddressType();
message.ToRecipients[0].EmailAddress = toEmailAddress;
message.ToRecipients[0].RoutingType = "SMTP";

//Note: Same you can set CC and BCC Recipients

// Construct the array of items to send
request.Items = new NonEmptyArrayOfAllItemsType();
request.Items.Items = new ItemType[1];
request.Items.Items[0] = message;

// Call the CreateItem EWS method.
CreateItemResponseType response = esb.CreateItem(request);
this.ThrowOnError("SendMessage", response.ResponseMessages.Items[0]);
}   

Adding the Attachments

public ItemIdType CreateAttachment(string name,string FilePath, ItemIdType p_signalId)
{
 ExchangeServiceBinding esb = new ExchangeServiceBinding();
    esb.Credentials = new NetworkCredential("user2", "password", "domain");
    esb.Url = "https://www.example.com/ews/exchange.asmx";

FileAttachmentType fileAttachment = null;

//Create add attachment request.
CreateAttachmentType attachementRequest = new CreateAttachmentType();

attachementRequest.ParentItemId = p_signalId;
attachementRequest.Attachments = new AttachmentType[intAttachmentsCount];

fileAttachment = new FileAttachmentType();
MessageBDO.AttachmentsDTRow drowAttachment
= (MessageBDO.AttachmentsDTRow)p_signal.AttachmentsDT.Rows[intIndex];

fileAttachment.Name =name;
fileAttachment.ContentType = "text/plain";
fileAttachment.Content = System.IO.File.ReadAllBytes(FilePath);
attachementRequest.Attachments[intIndex] = fileAttachment;

ItemIdType attachmentItemId = new ItemIdType();
CreateAttachmentResponseType response = 
	(CreateAttachmentResponseType)_esb.CreateAttachment(attachementRequest );
if (response.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Success)
{
AttachmentIdType attachmentId = ((AttachmentInfoResponseMessageType)
	response.ResponseMessages.Items[0]).Attachments[0].AttachmentId;
attachmentItemId.ChangeKey = attachmentId.RootItemChangeKey.ToString();
attachmentItemId.Id = attachmentId.RootItemId.ToString();
}
return attachmentItemId;
}

Now Sending the Mail

 //Here the itemID is returned by the CreateMessage Function         
public bool SendMessage(ItemIdType p_itemId)
 {
 bool blnResult = false;
 SendItemType siSendItem = new SendItemType();
 siSendItem.ItemIds = new BaseItemIdType[1];
 siSendItem.SavedItemFolderId = new TargetFolderIdType();
 DistinguishedFolderIdType siSentItemsFolder = new DistinguishedFolderIdType();
 siSentItemsFolder.Id = DistinguishedFolderIdNameType.sentitems;
 siSendItem.SavedItemFolderId.Item = siSentItemsFolder;
 siSendItem.SaveItemToFolder = true;
 
 siSendItem.ItemIds[0] = (BaseItemIdType)p_itemId;
 SendItemResponseType srSendItemResponseMessage = _esb.SendItem(siSendItem);
 if (srSendItemResponseMessage.ResponseMessages.Items[0].ResponseClass == 
	ResponseClassType.Success)
 {
 blnResult = true;
 }
 else
 {
 blnResult = false;
 }
 return blnResult;
 }  

Reference

License

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

About the Author

Brij


Member
Brij has done MCA from National Institute of Techlnology,Durgapur, West Bengal, India.He is currently working as a S/W Multinational from last two years. He has also done graduation in Comp Science from Lucknow University . He has a great passion to learn new Microsoft Tecnologies and lovet to share the Knowledge.

Language / Technology :
C#, ASP.NET, AJAX, XML, ADO.Net , Active Directory , Exchange Server 2007 (EWS) , LCS-2005, Jscript, PL/SQL, Web Services , SQL Server 2005

Application Server :
IIS 5.1, IIS 6, IIS 7

Performance Tool :
SQL Profiler, Rational Performance Tester (RPT), ANTS Profiler
Occupation: Software Developer (Senior)
Location: India India

Other popular Microsoft Exchange articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 64 (Total in Forum: 64) (Refresh)FirstPrevNext
GeneralHelp! 405 Method Not Allowed Error Pinmemberiiiiii16817:46 26 May '09  
GeneralRe: Help! 405 Method Not Allowed Error PinmemberBrij2:37 30 Jun '09  
QuestionCan the EWS interface be exposed in vb.net Pinmemberdprima5:54 1 May '09  
QuestionRe: Can the EWS interface be exposed in vb.net Pinmemberdprima8:11 1 May '09  
AnswerRe: Can the EWS interface be exposed in vb.net PinmemberBrij0:40 4 May '09  
QuestionProblems facing in programming Exchange 2007 using EWS PinmemberSamta_3:09 29 Apr '09  
AnswerRe: Problems facing in programming Exchange 2007 using EWS PinmemberBrij0:24 4 May '09  
QuestionAdmin acces PinmemberWired.Enterprises9:55 8 Apr '09  
QuestionCan't send to addresses that don't end in .com eg ian@xtra.co.nz Pinmemberparkerig16:25 16 Mar '09  
AnswerRe: Can't send to addresses that don't end in .com eg ian@xtra.co.nz PinmemberBrij0:41 9 Apr '09  
GeneralExchange Server 2003 PinmemberShahbaz Yousuf4:19 8 Mar '09  
GeneralRe: Exchange Server 2003 PinmemberBrij0:30 9 Apr '09  
GeneralError calling Exchange Pinmemberdride200614:36 7 Mar '09  
GeneralThrowOnError problem Pinmemberwilltmpw23:32 19 Feb '09  
GeneralRe: ThrowOnError problem PinmemberBrij0:58 25 Feb '09  
QuestionHow to get the ItemID of the newly created message in the Create Message method ? Pinmembermazfar15:15 29 Jan '09  
AnswerRe: How to get the ItemID of the newly created message in the Create Message method ? PinmemberBrij0:37 30 Jan '09  
GeneralRe: How to get the ItemID of the newly created message in the Create Message method ? Pinmembermazfar18:21 18 Feb '09  
GeneralProblems with ExchangeServiceBinding Pinmemberchrismalyon13:27 17 Jan '09  
GeneralRe: Problems with ExchangeServiceBinding PinmemberBrij19:07 18 Jan '09  
GeneralRe: Problems with ExchangeServiceBinding Pinmemberchrismalyon5:44 19 Jan '09  
GeneralHow to do progamming using exchange web server.... PinmemberMember 272372419:40 9 Jan '09  
GeneralRe: How to do progamming using exchange web server.... PinmemberBrij23:20 9 Jan '09  
GeneralRe: How to do progamming using exchange web server.... [modified] PinmemberMember 272372421:33 12 Jan '09  
GeneralRe: How to do progamming using exchange web server.... PinmemberBrij18:39 18 Jan '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 28 Aug 2008
Editor: Deeksha Shenoy
Copyright 2008 by Brij
Everything else Copyright © CodeProject, 1999-2009
Web20 | Advertise on the Code Project