Exchange Server 2007 WebService, Get Inbox Email Items – C#, SOAP Requests and Responses
I was evaluating the Exchange Server 2007 WebService API and trying to get a list of latest inbox items from EWS web service.
It took me a while to figure out the request objects and the way to configure all the parameters.
Here is the C# code doing this.
The ExchangePlay.exws Proxy was generated within Visual Studio by adding web reference to https://domainName/ews/Exchange.asmx?wsdl
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using ExchangePlay.exws;
namespace ExchangePlay
{
class Program
{
static void Main(string[] args)
{
ServicePointManager.ServerCertificateValidationCallback =
delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
// trust any certificate
return true;
};
ExchangeServiceBinding service = new ExchangeServiceBinding();
service.EnableDecompression = true; // enable compression
// your email account userName, password and the windows domain
service.Credentials = new NetworkCredential(“userName”, “password”, “windowsDomain”);
service.Url = @“https://domainName/EWS/Exchange.asmx”;
// find items first
FindItemResponseType response1 = service.FindItem(new FindItemType
{
ItemShape = new ItemResponseShapeType
{
BodyType = BodyTypeResponseType.Text,// body as text
BodyTypeSpecified = true
},
ParentFolderIds = new[]
{
new DistinguishedFolderIdType
{
Id = DistinguishedFolderIdNameType.inbox,//inbox items
}
},
SortOrder = new[]
{
new FieldOrderType
{
Item = new PathToUnindexedFieldType
{
FieldURI = UnindexedFieldURIType.itemDateTimeReceived
},
Order= SortDirectionType.Descending,
}
},
Item = new FractionalPageViewType
{
MaxEntriesReturned = 2, // 2 items only
MaxEntriesReturnedSpecified = true, // specify above property
Numerator = 1,
Denominator = 10 // 1/10 items
},
Traversal = ItemQueryTraversalType.Shallow,
});
// serialize response1 object for diagnostics purposes here
// find items details
GetItemResponseType response2 = service.GetItem(new GetItemType
{
ItemIds = ((response as FindItemResponseType)
.ResponseMessages
.Items
.Select(n => n as FindItemResponseMessageType)
.Select(n => n.RootFolder).Single().Item as ArrayOfRealItemsType)
.Items
.Select(n => new ItemIdType { Id = n.ItemId.Id })
.ToArray()
,
ItemShape = new ItemResponseShapeType
{
BaseShape = DefaultShapeNamesType.Default,
BodyType = BodyTypeResponseType.Text
}
});
// serialize response2 object for diagnostics purposes here
Console.WriteLine(“Finish”);
Console.ReadLine();
}
}
}
Sample XML requests and responses ( eliminated SOAP stuff )
<FindItemType xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=“http://www.w3.org/2001/XMLSchema” Traversal=“Shallow”>
<ItemShape xmlns=“http://schemas.microsoft.com/exchange/services/2006/messages”>
<BaseShape xmlns=“http://schemas.microsoft.com/exchange/services/2006/types”>IdOnly</BaseShape>
<BodyType xmlns=“http://schemas.microsoft.com/exchange/services/2006/types”>Text</BodyType>
</ItemShape>
<FractionalPageItemView MaxEntriesReturned=“2″ Numerator=“1″ Denominator=“10″ xmlns=“http://schemas.microsoft.com/exchange/services/2006/messages” />
<SortOrder xmlns=“http://schemas.microsoft.com/exchange/services/2006/messages”>
<FieldOrder Order=“Descending” xmlns=“http://schemas.microsoft.com/exchange/services/2006/types”>
<FieldURI FieldURI=“item:DateTimeReceived” />
</FieldOrder>
</SortOrder>
<ParentFolderIds xmlns=“http://schemas.microsoft.com/exchange/services/2006/messages”>
<DistinguishedFolderId Id=“inbox” xmlns=“http://schemas.microsoft.com/exchange/services/2006/types” />
</ParentFolderIds>
</FindItemType>
<FindItemResponseType xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=“http://www.w3.org/2001/XMLSchema”>
<ResponseMessages xmlns=“http://schemas.microsoft.com/exchange/services/2006/messages”>
<FindItemResponseMessage ResponseClass=“Success”>
<ResponseCode>NoError</ResponseCode>
<RootFolder NumeratorOffset=“30″ AbsoluteDenominator=“281″ IncludesLastItemInRange=“false” TotalItemsInView=“281″>
<Items xmlns=“http://schemas.microsoft.com/exchange/services/2006/types”>
<Message>
<ItemId Id=“a long string as the id” />
</Message>
<Message>
<ItemId Id=“a long string as the id” />
</Message>
</Items>
</RootFolder>
</FindItemResponseMessage>
</ResponseMessages>
</FindItemResponseType>
<!– getItems –>
<GetItemType xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=“http://www.w3.org/2001/XMLSchema”>
<ItemShape xmlns=“http://schemas.microsoft.com/exchange/services/2006/messages”>
<BaseShape xmlns=“http://schemas.microsoft.com/exchange/services/2006/types”>Default</BaseShape>
</ItemShape>
<ItemIds xmlns=“http://schemas.microsoft.com/exchange/services/2006/messages”>
<ItemId Id=“Aa long string as the id0″ xmlns=“http://schemas.microsoft.com/exchange/services/2006/types” />
<ItemId Id=“a long string as the id1″ xmlns=“http://schemas.microsoft.com/exchange/services/2006/types” />
</ItemIds>
</GetItemType>
<GetItemResponseType xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=“http://www.w3.org/2001/XMLSchema”>
<ResponseMessages xmlns=“http://schemas.microsoft.com/exchange/services/2006/messages”>
<GetItemResponseMessage ResponseClass=“Success”>
<ResponseCode>NoError</ResponseCode>
<Items>
<Message xmlns=“http://schemas.microsoft.com/exchange/services/2006/types”>
<ItemId Id=“a long string as the id” ChangeKey=“CQAAABYAAADvx0sPONNNTJ6Xrl3TwTggADSHYbhk” />
<Subject>RE: hello</Subject>
<Sensitivity>Normal</Sensitivity>
<Body BodyType=“HTML”>
mail body goes here
</Body>
<Attachments>
<FileAttachment>
<AttachmentId Id=“long string here as id” />
<Name>image002.jpg</Name>
<ContentType>image/jpeg</ContentType>
<ContentId>image002.jpg@01C9DAD3.2C0F88E0</ContentId>
</FileAttachment>
</Attachments>
<Size>36483</Size>
<DateTimeSent>2009-05-21T23:48:06Z</DateTimeSent>
<DateTimeCreated>2009-05-21T23:48:09Z</DateTimeCreated>
<ResponseObjects>
<ReplyToItem />
<ReplyAllToItem />
<ForwardItem />
</ResponseObjects>
<HasAttachments>false</HasAttachments>
<ToRecipients>
<Mailbox>
<Name>WallE</Name>
<EmailAddress>email1@example.com</EmailAddress>
<RoutingType>SMTP</RoutingType>
</Mailbox>
</ToRecipients>
<CcRecipients>
<Mailbox>
<Name>WallE-II</Name>
<EmailAddress>Dorothy.Rowe@example.com</EmailAddress>
<RoutingType>SMTP</RoutingType>
</Mailbox>
</CcRecipients>
<IsReadReceiptRequested>false</IsReadReceiptRequested>
<IsDeliveryReceiptRequested>false</IsDeliveryReceiptRequested>
<From>
<Mailbox>
<Name>WallE</Name>
<EmailAddress>email1@example.com</EmailAddress>
<RoutingType>SMTP</RoutingType>
</Mailbox>
</From>
<IsRead>true</IsRead>
</Message>
</Items>
</GetItemResponseMessage>
<GetItemResponseMessage ResponseClass=“Success”>
<ResponseCode>NoError</ResponseCode>
<Items>
<Message xmlns=“http://schemas.microsoft.com/exchange/services/2006/types”>
<ItemId Id=a long string as the id“” ChangeKey=“CQAAABYAAADvx0sPONNNTJ6Xrl3TwTggADSHYaqZ” />
<Subject>Hi</Subject>
<Sensitivity>Normal</Sensitivity>
<Body BodyType=“HTML”>
email body text
</Body>
<Attachments>
<FileAttachment>
<AttachmentId Id=“long id string here” />
<Name>image001.jpg</Name>
<ContentType>image/jpeg</ContentType>
<ContentId>image001.jpg@01C9DAC7.2F1C9840</ContentId>
</FileAttachment>
</Attachments>
<Size>13446</Size>
<DateTimeSent>2009-05-21T22:22:18Z</DateTimeSent>
<DateTimeCreated>2009-05-21T22:22:20Z</DateTimeCreated>
<ResponseObjects>
<ReplyToItem />
<ReplyAllToItem />
<ForwardItem />
</ResponseObjects>
<HasAttachments>false</HasAttachments>
<ToRecipients>
<Mailbox>
<Name>WallE</Name>
<EmailAddress>email1@example.com</EmailAddress>
<RoutingType>SMTP</RoutingType>
</Mailbox>
</ToRecipients>
<IsReadReceiptRequested>false</IsReadReceiptRequested>
<IsDeliveryReceiptRequested>false</IsDeliveryReceiptRequested>
<From>
<Mailbox>
<Name>WallE-II</Name>
<EmailAddress>wall3@example.com</EmailAddress>
<RoutingType>SMTP</RoutingType>
</Mailbox>
</From>
<IsRead>true</IsRead>
</Message>
</Items>
</GetItemResponseMessage>
</ResponseMessages>
</GetItemResponseType>
Hopefully you find this piece of quick note useful.
10 Responses to “Exchange Server 2007 WebService, Get Inbox Email Items – C#, SOAP Requests and Responses”
Comment from Saqib
Time September 20, 2009 at 1:02 pm
Alternatively, you may use a 3rd party library from Aspose to connect to Exchange mailbox using Exchange Web Services. You need to call the appropriate methods to connect and download messages. More details at .
Comment from Shahzad
Time April 8, 2010 at 9:10 pm
I have tested the code I receive following error:
The request failed with HTTP status 401: Unauthorized. Can anyone guide this.
Thanks
Comment from Ray
Time April 9, 2010 at 10:05 pm
Did you set the credential correcly?
service.Credentials = new NetworkCredential(“userName”, “password”, “windowsDomain”);
Comment from Naveed Mazhar
Time April 29, 2010 at 9:08 pm
Please explain “response” in the code given below.
“response” has not been declared in the code but response1 and response2 are present.
—————————————————————-
// find items details
GetItemResponseType response2 = service.GetItem(new GetItemType
{
ItemIds = ((response as FindItemResponseType)
—————————————————————-
Comment from Bruce
Time May 20, 2010 at 3:37 am
Thanks. Almighty google has sent me on the code that’s just what i’ve searvhed for ![]()
Regards.
Comment from Ian Penny
Time September 10, 2010 at 3:22 am
I have recently found this code via google, after having an exchange box installed in our school. i have the code typed up, but what arguements do you pass in to obtain a response?
Comment from Ray
Time September 10, 2010 at 6:03 pm
@Ian, you will need to provide the following values in order to get a valid response.
service.Credentials = new NetworkCredential(“userName”, “password”, “windowsDomain”);
service.Url = @“https://domainName/EWS/Exchange.asmx”;
Comment from Ian Penny
Time September 10, 2010 at 11:12 pm
Hi Ray,
Thanks for your prompt reply, I have hard coded those items, so i have just removed the args and call the method.
Comment from Hank
Time October 4, 2011 at 1:19 am
Hey guys, I have more than 3 days tried to pass the current credentials to the exchang.asmx service. I tried crendentialcache and contexwindowIdentity impersonation but not luck.
Some idea how I can use the current user credentials to get users appointments.
Thanks
Hank
Comment from Uncleedik
Time July 22, 2009 at 10:08 am
Thanks. Almighty google has sent me on the code that’s just what i’ve searvhed for
Regards.