using System;
using System.Net;
using System.Collections.Generic;
using EWS;
using MailClient;

namespace ExchangeWs {
public class ExchangeWs {
private ExchangeServiceBinding esb = null;
private GetExchangeSetting ExchangeSetting = new GetExchangeSetting();

public ExchangeWs(string userAccount, string password, string domain, string url) {
esb = new ExchangeServiceBinding();
esb.Credentials = new NetworkCredential(userAccount, password, domain);
if (esb.RequestServerVersionValue == null) {
esb.RequestServerVersionValue = new RequestServerVersion();
esb.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007_SP1;
}
esb.Url = url;
}

#region GetOWAId
public string GetOWAId(string EWSId, string mailAddress) {
// Create the request.
ConvertIdType request = new ConvertIdType();
request.SourceIds = new AlternateIdType[1];
request.SourceIds[0] = new AlternateIdType();

// Convert from the Exchange Web Services identifier to an Outlook Web Access identifier.
request.SourceIds[0].Format = IdFormatType.EwsId;
(request.SourceIds[0] as AlternateIdType).Id = EWSId;
(request.SourceIds[0] as AlternateIdType).Mailbox = mailAddress;// "TestUser1@cqyz.cn";
request.DestinationFormat = IdFormatType.OwaId;

 

string result = null;

try {
// Send the ConvertIdType request and get the response.
ConvertIdResponseType response = esb.ConvertId(request);
ArrayOfResponseMessagesType aormt = response.ResponseMessages;
ResponseMessageType[] rmta = aormt.Items;

// Check each response message.
if (rmta != null && rmta.Length > 0) {
ConvertIdResponseMessageType resp = (ConvertIdResponseMessageType)rmta[0];
if (resp != null) {
if (resp.ResponseClass == ResponseClassType.Success) {
ConvertIdResponseMessageType cirmt = (resp as ConvertIdResponseMessageType);
AlternateIdType myId = (cirmt.AlternateId as AlternateIdType);

string format = myId.Format.ToString();
string identifier = myId.Id;
string mailbox = myId.Mailbox;

result = identifier;
}
}
}
} catch {
}
return result;
}
#endregion

#region Restriction
private RestrictionType GetCalendarRestrictionByTime(DateTime? start, DateTime? end) {
if (start == null || end == null)
return null;

RestrictionType restriction = new RestrictionType();

AndType and = new AndType();
SearchExpressionType[] searchExpressions = new SearchExpressionType[2];

///////////////////////////////////////////////////////////////////////////
//设定IsGreaterThanOrEqualTo
///////////////////////////////////////////////////////////////////////////
IsGreaterThanOrEqualToType isGTOET = new IsGreaterThanOrEqualToType();

//define FieldURIOrConstant
FieldURIOrConstantType fieldURIOrConstantType = new FieldURIOrConstantType();
ConstantValueType constant = new ConstantValueType();
constant.Value = start.ToString();
fieldURIOrConstantType.Item = constant;

//define FieldURI
PathToUnindexedFieldType pathToUnindexedFieldType = new PathToUnindexedFieldType();
pathToUnindexedFieldType.FieldURI = UnindexedFieldURIType.calendarStart;

isGTOET.Item = pathToUnindexedFieldType;
isGTOET.FieldURIOrConstant = fieldURIOrConstantType;
searchExpressions[0] = isGTOET;

///////////////////////////////////////////////////////////////////////////
//设定IsLessThanOrEqualTo
///////////////////////////////////////////////////////////////////////////
IsLessThanOrEqualToType isLTOET = new IsLessThanOrEqualToType();

//define FieldURIOrConstant
FieldURIOrConstantType _fieldURIOrConstantType = new FieldURIOrConstantType();
ConstantValueType _constant = new ConstantValueType();
_constant.Value = end.ToString();
_fieldURIOrConstantType.Item = _constant;

//define FieldURI
PathToUnindexedFieldType _pathToUnindexedFieldType = new PathToUnindexedFieldType();
_pathToUnindexedFieldType.FieldURI = UnindexedFieldURIType.calendarEnd;

isLTOET.Item = _pathToUnindexedFieldType;
isLTOET.FieldURIOrConstant = _fieldURIOrConstantType;
searchExpressions[1] = isLTOET;

and.Items = searchExpressions;

restriction.Item = and;

return restriction;
}

private RestrictionType GetMailRestrictionByUnRead() {
RestrictionType restriction = new RestrictionType();
IsEqualToType isEqual = new IsEqualToType();

FieldURIOrConstantType _fieldURIOrConstantType = new FieldURIOrConstantType();
ConstantValueType _constant = new ConstantValueType();
_constant.Value = "0";
_fieldURIOrConstantType.Item = _constant;

PathToUnindexedFieldType _pathToUnindexedFieldType = new PathToUnindexedFieldType();
_pathToUnindexedFieldType.FieldURI = UnindexedFieldURIType.messageIsRead;

isEqual.FieldURIOrConstant = _fieldURIOrConstantType;
isEqual.Item = _pathToUnindexedFieldType;

restriction.Item = isEqual;

return restriction;
}
#endregion

#region GetCalendar
public List<CalendarItemType> GetCalendar(DateTime? start, DateTime? end) {
FindItemType findItemRequest = new FindItemType();
findItemRequest.Traversal = ItemQueryTraversalType.Shallow;

ItemResponseShapeType itemProperties = new ItemResponseShapeType();
itemProperties.BaseShape = DefaultShapeNamesType.AllProperties;

findItemRequest.ItemShape = itemProperties;

//查询条件
RestrictionType restriction = GetCalendarRestrictionByTime(start, end);

if (restriction != null)
findItemRequest.Restriction = restriction;

DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
folderIDArray[0] = new DistinguishedFolderIdType();
folderIDArray[0].Id = DistinguishedFolderIdNameType.calendar;

findItemRequest.ParentFolderIds = folderIDArray;

try {
FindItemResponseType findItemResponse = esb.FindItem(findItemRequest);

ResponseMessageType[] rmta = findItemResponse.ResponseMessages.Items;

return getCalendar(ref rmta);
} catch (Exception e) {
throw (e);
}
}

private List<CalendarItemType> getCalendar(ref ResponseMessageType[] rmta) {
List<CalendarItemType> calendars = new List<CalendarItemType>(30);
if (rmta != null) {
foreach (ResponseMessageType rmt in rmta) {
if (rmt is FindItemResponseMessageType) {
FindItemResponseMessageType findItemResponse = (FindItemResponseMessageType)rmt;
if (findItemResponse.ResponseClass == ResponseClassType.Success) {
if (findItemResponse.RootFolder.Item is ArrayOfRealItemsType) {
ArrayOfRealItemsType obj = (ArrayOfRealItemsType)findItemResponse.RootFolder.Item;

if (obj != null && obj.Items != null) {
foreach (ItemType item in obj.Items) {
if (item is CalendarItemType) {
CalendarItemType calendarItem = (CalendarItemType)item;
if (calendarItem != null) {
calendars.Add(calendarItem);
}
}
}
}
}
}
}
}
}

return calendars;
}
#endregion

#region GetNewMail
public List<MessageType> GetNewMail() {
FindItemType findItemRequest = new FindItemType();
findItemRequest.Traversal = ItemQueryTraversalType.Shallow;

ItemResponseShapeType itemProperties = new ItemResponseShapeType();
itemProperties.BaseShape = DefaultShapeNamesType.AllProperties;

findItemRequest.ItemShape = itemProperties;

DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
folderIDArray[0] = new DistinguishedFolderIdType();
folderIDArray[0].Id = DistinguishedFolderIdNameType.inbox;

findItemRequest.ParentFolderIds = folderIDArray;

//查询条件
RestrictionType restriction = GetMailRestrictionByUnRead();

if (restriction != null)
findItemRequest.Restriction = restriction;

try {
FindItemResponseType findItemResponse = esb.FindItem(findItemRequest);

ResponseMessageType[] rmta = findItemResponse.ResponseMessages.Items;

return getMail(ref rmta);
} catch (Exception e) {
throw (e);
}
}

private List<MessageType> getMail(ref ResponseMessageType[] rmta) {
List<MessageType> newMails = new List<MessageType>(30);
if (rmta != null) {
foreach (ResponseMessageType rmt in rmta) {
if (rmt is FindItemResponseMessageType) {
FindItemResponseMessageType findItemResponse = (FindItemResponseMessageType)rmt;
if (findItemResponse.ResponseClass == ResponseClassType.Success) {
if (findItemResponse.RootFolder.Item is ArrayOfRealItemsType) {
ArrayOfRealItemsType obj = (ArrayOfRealItemsType)findItemResponse.RootFolder.Item;

if (obj != null && obj.Items != null) {
foreach (ItemType item in obj.Items) {
if (item is MessageType) {
MessageType message = (MessageType)item;
if (message != null) {
newMails.Add(message);
}
}
}
}
}
}
}
}
}

return newMails;
}
#endregion

#region MailQuota
public MailQuota GetUsedMailboxSize() {
GetFolderType request = new GetFolderType();
PathToExtendedFieldType folderSizePath = new PathToExtendedFieldType();
folderSizePath.PropertyTag = "0x0e08";
folderSizePath.PropertyType = MapiPropertyTypeType.Integer;

FolderResponseShapeType folderResponseShapeType = new FolderResponseShapeType();
folderResponseShapeType.BaseShape = DefaultShapeNamesType.AllProperties;
folderResponseShapeType.AdditionalProperties = new BasePathToElementType[] { folderSizePath };

DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[13];
folderIDArray[0] = new DistinguishedFolderIdType();
folderIDArray[0].Id = DistinguishedFolderIdNameType.sentitems;

folderIDArray[1] = new DistinguishedFolderIdType();
folderIDArray[1].Id = DistinguishedFolderIdNameType.drafts;

folderIDArray[2] = new DistinguishedFolderIdType();
folderIDArray[2].Id = DistinguishedFolderIdNameType.voicemail;

folderIDArray[3] = new DistinguishedFolderIdType();
folderIDArray[3].Id = DistinguishedFolderIdNameType.calendar;

folderIDArray[4] = new DistinguishedFolderIdType();
folderIDArray[4].Id = DistinguishedFolderIdNameType.contacts;

folderIDArray[5] = new DistinguishedFolderIdType();
folderIDArray[5].Id = DistinguishedFolderIdNameType.tasks;

folderIDArray[6] = new DistinguishedFolderIdType();
folderIDArray[6].Id = DistinguishedFolderIdNameType.deleteditems;

folderIDArray[7] = new DistinguishedFolderIdType();
folderIDArray[7].Id = DistinguishedFolderIdNameType.inbox;

folderIDArray[8] = new DistinguishedFolderIdType();
folderIDArray[8].Id = DistinguishedFolderIdNameType.journal;

folderIDArray[9] = new DistinguishedFolderIdType();
folderIDArray[9].Id = DistinguishedFolderIdNameType.junkemail;

folderIDArray[10] = new DistinguishedFolderIdType();
folderIDArray[10].Id = DistinguishedFolderIdNameType.searchfolders;

folderIDArray[11] = new DistinguishedFolderIdType();
folderIDArray[11].Id = DistinguishedFolderIdNameType.notes;

folderIDArray[12] = new DistinguishedFolderIdType();
folderIDArray[12].Id = DistinguishedFolderIdNameType.outbox;

request.FolderIds = folderIDArray;
request.FolderShape = folderResponseShapeType;

GetFolderResponseType response = esb.GetFolder(request);

return parseQuota(response);
}

private MailQuota parseQuota(GetFolderResponseType response) {
MailQuota quota = null;
if (response == null)
return quota;

ArrayOfResponseMessagesType arrayOfResponseMessagesType = response.ResponseMessages;
if (arrayOfResponseMessagesType == null)
return quota;

ResponseMessageType[] responseMessageType = arrayOfResponseMessagesType.Items;
if (responseMessageType == null || responseMessageType.Length == 0)
return quota;

quota = new MailQuota();

for (int i = 0; i < responseMessageType.Length; i++) {
FolderInfoResponseMessageType folderInfoResponseMessage = responseMessageType[i] as FolderInfoResponseMessageType;
if (folderInfoResponseMessage == null)
continue;

BaseFolderType[] folders = folderInfoResponseMessage.Folders;

if (folders == null || folders.Length == 0)
continue;

BaseFolderType folder = null;
if (folders[0] is CalendarFolderType)
folder = folders[0] as CalendarFolderType;
else if (folders[0] is ContactsFolderType)
folder = folders[0] as ContactsFolderType;
else
folder = folders[0] as FolderType;

if (folder == null)
continue;

ExtendedPropertyType[] extendedPropertys = folder.ExtendedProperty;
if (extendedPropertys == null)
continue;
if (extendedPropertys.Length == 0)
continue;

ExtendedPropertyType extendedProperty = extendedPropertys[0];
if (extendedProperty == null)
continue;

int temp = 0;
int.TryParse(extendedProperty.Item.ToString(), out temp);
quota.UsedQuota += temp;

quota.MailCount += folder.TotalCount;
if (folder is FolderType)
quota.UnReadMailCount += ((EWS.FolderType)(folder)).UnreadCount;
}

return quota;
}
#endregion

#region SendMail
public bool SendMail(Mail m) {
EWS.CreateItemType createItem = new EWS.CreateItemType();
createItem.MessageDispositionSpecified = true;
createItem.MessageDisposition = EWS.MessageDispositionType.SendOnly;
EWS.MessageType message = new EWS.MessageType();
message.ItemClass = "IPM.Note";
message.Subject = m.Subject;
BodyType body = new BodyType();
body.BodyType1 = BodyTypeType.Text;
body.Value = m.Content;
message.Body = body;
message.IsRead = false;

message.ToRecipients = splitAddress(m.Address.To);

message.CcRecipients = splitAddress(m.Address.Cc);

message.BccRecipients = splitAddress(m.Address.Bcc);

createItem.Items = new NonEmptyArrayOfAllItemsType();
createItem.Items.Items = new EWS.ItemType[] { message };

CreateItemResponseType response = esb.CreateItem(createItem);
return response.ResponseMessages.Items[0].ResponseCode == ResponseCodeType.NoError;
}

private EWS.EmailAddressType[] splitAddress(string addr) {
if (String.IsNullOrEmpty(addr))
return null;

string[] arr = addr.Split(",;".ToCharArray());
List<EWS.EmailAddressType> list = new List<EmailAddressType>(arr.Length);
foreach (string str in arr) {
if (!String.IsNullOrEmpty(str)) {
EmailAddressType address = new EmailAddressType();
address.EmailAddress = str;

list.Add(address);
}
}
return list.ToArray();
}
#endregion
}
}

posted on 2013-03-20 15:59  袁晓平  阅读(1626)  评论(0编辑  收藏  举报