通过exchange web service收发邮件

    最近做通过ews收发exchange邮件,又有不小收获,下面说下遇到的问题及解决办法

    主要是用ExchangeServiceBinding来进行邮件操作

    1.exchange服务器安全证书,就是用于测试的exchange服务器的证书不被信任,由于是测试当然没有申请合适的证书,然后ews会验证服务器的证书,所以报错,解决方法:

    public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; } static EWS() { ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); } 

    2.发送邮件,不带附件

     ///

/// 发送邮件 /// /// 邮件实体信息 /// public bool SendMail(COEmailInfo mail) { // Create the CreateItem request. CreateItemType createItemRequest = new CreateItemType(); // Specifiy how the created items are handled createItemRequest.MessageDisposition = MessageDispositionType.SendAndSaveCopy; createItemRequest.MessageDispositionSpecified = true; // Specify the location of sent items. createItemRequest.SavedItemFolderId = new TargetFolderIdType(); DistinguishedFolderIdType sentitems = new DistinguishedFolderIdType(); sentitems.Id = DistinguishedFolderIdNameType.sentitems; createItemRequest.SavedItemFolderId.Item = sentitems; // Create the array of items. createItemRequest.Items = new NonEmptyArrayOfAllItemsType(); // Create a single e-mail message. MessageType message = new MessageType(); message.Subject = mail.Superscription; message.Body = new BodyType(); message.Body.BodyType1 = BodyTypeType.HTML; message.Body.Value = mail.StraightMatter; message.ItemClass = "IPM.Note"; message.Sender = new SingleRecipientType(); message.Sender.Item = new EmailAddressType(); message.Sender.Item.EmailAddress = mail.Addresser; message.ToRecipients = new EmailAddressType[1]; message.ToRecipients[0] = new EmailAddressType(); message.ToRecipients[0].EmailAddress = mail.Addressee; message.Sensitivity = SensitivityChoicesType.Normal; // Add the message to the array of items to be created. createItemRequest.Items.Items = new ItemType[1]; createItemRequest.Items.Items[0] = message; // Send the request to create and send the e-mail item, and get the response. CreateItemResponseType createItemResponse = _esb.CreateItem(createItemRequest); // Determine whether the request was a success. if (createItemResponse.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Error) { throw new Exception(createItemResponse.ResponseMessages.Items[0].MessageText); } AddToDatabase(mail, null); return true; }

    3.发送邮件,带附件,这里需要注意,如果是大附件的话,首先要exchange那边设置附件大小,然后是设置ews服务的http超时(iis),默认是120s,如果网速不行传输时间大于120还是会报错,主要是因为http传输,带附件的邮件分3步,一是发邮件到草稿箱,二是给刚才的邮件添加附件,三是发送刚才草稿箱的邮件。

 

     ///

/// 发送带附件的邮件 /// /// 邮件实体 /// 附件列表 /// public bool SendMailWithAttachments(COEmailInfo mail, List attachments) { if (attachments == null || attachments.Count == 0) { SendMail(mail); } // Create a single e-mail message. MessageType message = new MessageType(); message.Subject = mail.Superscription; message.Body = new BodyType(); message.Body.BodyType1 = BodyTypeType.HTML; message.Body.Value = mail.StraightMatter; message.ItemClass = "IPM.Note"; message.Sender = new SingleRecipientType(); message.Sender.Item = new EmailAddressType(); message.Sender.Item.EmailAddress = this._username + "@" + this._domain; message.ToRecipients = new EmailAddressType[1]; message.ToRecipients[0] = new EmailAddressType(); message.ToRecipients[0].EmailAddress = mail.Addressee; message.Sensitivity = SensitivityChoicesType.Normal; ItemIdType iiCreateItemid = CreateDraftMessage(message); iiCreateItemid = CreateAttachment(attachments, iiCreateItemid); SendMessage(iiCreateItemid); AddToDatabase(mail, attachments); return true; } //给邮件添加附件 private ItemIdType CreateAttachment(List attachments, ItemIdType iiCreateItemid) { ItemIdType iiAttachmentItemid = new ItemIdType(); CreateAttachmentType amAttachmentMessage = new CreateAttachmentType(); amAttachmentMessage.Attachments = new AttachmentType[attachments.Count]; int count = 0; foreach (COMailAttachment attach in attachments) { FileStream fsFileStream = new FileStream(this._attachSavePath + attach.FileURL, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] bdBinaryData = new byte[fsFileStream.Length]; long brBytesRead = fsFileStream.Read(bdBinaryData, 0, (int)fsFileStream.Length); fsFileStream.Close(); FileAttachmentType faFileAttach = new FileAttachmentType(); faFileAttach.Content = bdBinaryData; faFileAttach.Name = attach.Name; amAttachmentMessage.Attachments[count++] = faFileAttach; } amAttachmentMessage.ParentItemId = iiCreateItemid; CreateAttachmentResponseType caCreateAttachmentResponse = this._esb.CreateAttachment(amAttachmentMessage); if (caCreateAttachmentResponse.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Error) { throw new Exception(caCreateAttachmentResponse.ResponseMessages.Items[0].MessageText); } else { AttachmentInfoResponseMessageType amAttachmentResponseMessage = caCreateAttachmentResponse.ResponseMessages.Items[0] as AttachmentInfoResponseMessageType; iiAttachmentItemid.Id = amAttachmentResponseMessage.Attachments[0].AttachmentId.RootItemId.ToString(); iiAttachmentItemid.ChangeKey = amAttachmentResponseMessage.Attachments[0].AttachmentId.RootItemChangeKey.ToString(); } return iiAttachmentItemid; } //创建草稿箱邮件 private ItemIdType CreateDraftMessage(MessageType emMessage) { ItemIdType iiItemid = new ItemIdType(); CreateItemType ciCreateItemRequest = new CreateItemType(); ciCreateItemRequest.MessageDisposition = MessageDispositionType.SaveOnly; ciCreateItemRequest.MessageDispositionSpecified = true; ciCreateItemRequest.SavedItemFolderId = new TargetFolderIdType(); DistinguishedFolderIdType dfDraftsFolder = new DistinguishedFolderIdType(); dfDraftsFolder.Id = DistinguishedFolderIdNameType.drafts; ciCreateItemRequest.SavedItemFolderId.Item = dfDraftsFolder; ciCreateItemRequest.Items = new NonEmptyArrayOfAllItemsType(); ciCreateItemRequest.Items.Items = new ItemType[1]; ciCreateItemRequest.Items.Items[0] = emMessage; CreateItemResponseType createItemResponse = this._esb.CreateItem(ciCreateItemRequest); if (createItemResponse.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Error) { throw new Exception(createItemResponse.ResponseMessages.Items[0].MessageText); } else { ItemInfoResponseMessageType rmResponseMessage = createItemResponse.ResponseMessages.Items[0] as ItemInfoResponseMessageType; iiItemid.Id = rmResponseMessage.Items.Items[0].ItemId.Id.ToString(); iiItemid.ChangeKey = rmResponseMessage.Items.Items[0].ItemId.ChangeKey.ToString(); } return iiItemid; } //发送草稿箱邮件 private void SendMessage(ItemIdType iiCreateItemid) { 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)iiCreateItemid; SendItemResponseType srSendItemReponseMessage = this._esb.SendItem(siSendItem); if (srSendItemReponseMessage.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Error) { throw new Exception(srSendItemReponseMessage.ResponseMessages.Items[0].MessageText); } } 

    发送带回执的邮件只需在发送邮件时指明message的IsReadReceiptRequested和IsReadReceiptRequestedSpecified属性为true

    4.收邮件,主要是注意邮件的内联附件

     ///

/// 获取指定文件夹的邮件 /// /// 文件夹类型 /// 是否只下载已读 /// public COEmailInfo[] GetMails(DistinguishedFolderIdNameType type, bool isUnReadOnly, List attachments) { FindItemType request = new FindItemType(); request.ItemShape = new ItemResponseShapeType(); request.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties; DistinguishedFolderIdType folder = new DistinguishedFolderIdType(); folder.Id = type; request.ParentFolderIds = new BaseFolderIdType[] { folder }; request.Traversal = ItemQueryTraversalType.Shallow; //just get the list of unread messages if (isUnReadOnly) { RestrictionType restrict = new RestrictionType(); IsEqualToType isEqTo = new IsEqualToType(); PathToUnindexedFieldType ptuift = new PathToUnindexedFieldType(); ptuift.FieldURI = UnindexedFieldURIType.messageIsRead; isEqTo.Item = ptuift; FieldURIOrConstantType msgReadYes = new FieldURIOrConstantType(); msgReadYes.Item = new ConstantValueType(); (msgReadYes.Item as ConstantValueType).Value = "0"; //1= boolean yes; so you'll get the list of read messages isEqTo.FieldURIOrConstant = msgReadYes; restrict.Item = isEqTo; request.Restriction = restrict; } FindItemResponseType response = this._esb.FindItem(request); FindItemResponseMessageType responseMessage = response.ResponseMessages.Items[0] as FindItemResponseMessageType; ItemType[] messages = (responseMessage.RootFolder.Item as ArrayOfRealItemsType).Items; List mails = new List(); if (messages != null) { foreach (ItemType it in messages) { COEmailInfo mail = new COEmailInfo(); bool isAdd = false; GetItemType g = new GetItemType(); g.ItemShape = new ItemResponseShapeType(); g.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties; g.ItemIds = new BaseItemIdType[] { it.ItemId }; GetItemResponseType p_mailResponse = _esb.GetItem(g); ArrayOfResponseMessagesType arrMail = p_mailResponse.ResponseMessages; ResponseMessageType[] responseMessages = arrMail.Items; foreach (ResponseMessageType respmsg in responseMessages) { if (respmsg.ResponseClass == ResponseClassType.Error) { throw new Exception("Error: " + respmsg.MessageText); } else if (respmsg.ResponseClass == ResponseClassType.Warning) { throw new Exception("Error: " + respmsg.MessageText); } //check to determine whether the response message is correct type if (respmsg is ItemInfoResponseMessageType) { ItemInfoResponseMessageType createItemResp = (respmsg as ItemInfoResponseMessageType); ArrayOfRealItemsType aorit = createItemResp.Items; foreach (MessageType myMessage in aorit.Items) { if (myMessage.IsReadSpecified && myMessage.IsRead && isUnReadOnly) { mail.EmailState = 1; continue; } else { mail.EmailState = 2; } isAdd = true; mail.Superscription = myMessage.Subject; if (string.IsNullOrEmpty(mail.Superscription)) { mail.Superscription = "无标题"; } if (myMessage.Body.BodyType1 == BodyTypeType.Text) { mail.StraightMatter = myMessage.Body.Value.Replace(Environment.NewLine, "
"); } else { mail.StraightMatter = myMessage.Body.Value; } if (mail.StraightMatter == null) { mail.StraightMatter = string.Empty; } if (myMessage.From != null) { mail.Addresser = myMessage.From.Item.EmailAddress; } mail.Addressee = this._username + "@" + this._domain; if (myMessage.DateTimeReceivedSpecified) { //+8 mail.CreateTime = myMessage.DateTimeReceived.AddHours(8); } //mail.ID = mibll.Add(mail); List mailattachs = null; if (myMessage.HasAttachmentsSpecified && myMessage.HasAttachments) { mailattachs = DownloadAttachments(myMessage.ItemId, 0); mail.HasAttachments = true; attachments.AddRange(mailattachs); } else { mail.HasAttachments = false; } mail.StraightMatter = GetInlineFiles(myMessage, mail.StraightMatter); AddToDatabase(mail, mailattachs); SetReadStatus(it.ItemId); } } } if (isAdd) { mails.Add(mail); } } } return mails.ToArray(); } /// /// 获取对应的内联附件 /// /// 邮件 /// 邮件正文 /// private string GetInlineFiles(MessageType msg, string body) { if(msg.Attachments != null) { Regex reg = new Regex(@"src=""cid:([^""]+)""", RegexOptions.IgnoreCase); MatchCollection mcs = reg.Matches(body); foreach (AttachmentType attach in msg.Attachments) { foreach (Match mc in mcs) { //mc.g if (mc.Groups.Count == 2) { if (attach.ContentId == mc.Groups[1].Value) { AttachmentResponseShapeType arst = null; AttachmentIdType[] aita = null; //create the attachment shape; we want the mime contnet just in case this is an message item so that we can save to disk arst = new AttachmentResponseShapeType(); arst.IncludeMimeContent = true; arst.IncludeMimeContentSpecified = true; //create an array of attachment ids that we want to request aita = new AttachmentIdType[1]; aita[0] = new AttachmentIdType(); aita[0].Id = attach.AttachmentId.Id; //create a GetAttachment object for the GetAttachment operation GetAttachmentType gat = new GetAttachmentType(); gat.AttachmentIds = aita; gat.AttachmentShape = arst; GetAttachmentResponseType gart = _esb.GetAttachment(gat); string ext = string.Empty; string savePath = string.Empty; //save each attachment to disk foreach (AttachmentInfoResponseMessageType Attachment in gart.ResponseMessages.Items) { switch (Attachment.Attachments[0].GetType().Name) { //attachments can be of type FileAttachmentType or ItemAttachmentType //so we need to figure out which type we have before we manipulate it case "FileAttachmentType": //save to disk FileAttachmentType TheFileAttachment = (FileAttachmentType)Attachment.Attachments[0]; ext = Path.GetExtension(Attachment.Attachments[0].Name); savePath = this._siteid + "/" + Guid.NewGuid().ToString() + ext; using (Stream FileToDisk = new FileStream(this._attachSavePath + savePath, FileMode.Create)) { FileToDisk.Write(TheFileAttachment.Content, 0, TheFileAttachment.Content.Length); FileToDisk.Flush(); FileToDisk.Close(); body = body.Replace("cid:" + attach.ContentId, CacheConstants.MailAttachmentsPath.Replace("~", "") + savePath); } break; case "ItemAttachmentType": ItemType TheItemAttachment = ((ItemAttachmentType)Attachment.Attachments[0]).Item; ext = Path.GetExtension(Attachment.Attachments[0].Name); savePath = this._siteid + "/" + Guid.NewGuid().ToString() + ext; using (Stream FileToDisk = new FileStream(this._attachSavePath + savePath, FileMode.Create)) { byte[] ContentBytes = System.Convert.FromBase64String(TheItemAttachment.MimeContent.Value); FileToDisk.Write(ContentBytes, 0, ContentBytes.Length); FileToDisk.Flush(); FileToDisk.Close(); body = body.Replace("cid:" + attach.ContentId, CacheConstants.MailAttachmentsPath.Replace("~", "") + savePath); } break; default: break; } } } } } } } return body; } /// /// 下载某个邮件的附件 /// /// 邮件 /// public List DownloadAttachments(ItemIdType iit, int mailid) { //first we need to get the attachment IDs for the item so we will need to make a GetItem call first //specify the conetent that we want to retrieve PathToUnindexedFieldType[] ptufta = new PathToUnindexedFieldType[2]; ptufta[0] = new PathToUnindexedFieldType(); ptufta[0].FieldURI = UnindexedFieldURIType.itemAttachments; ptufta[1] = new PathToUnindexedFieldType(); ptufta[1].FieldURI = UnindexedFieldURIType.itemHasAttachments; ItemResponseShapeType irst = new ItemResponseShapeType(); irst.BaseShape = DefaultShapeNamesType.IdOnly; irst.AdditionalProperties = ptufta; ItemIdType[] biita = new ItemIdType[1]; biita[0] = new ItemIdType(); biita[0].Id = iit.Id; //get the items GetItemType git = new GetItemType(); git.ItemShape = irst; git.ItemIds = biita; GetItemResponseType girt = _esb.GetItem(git); if (girt.ResponseMessages.Items[0].ResponseClass != ResponseClassType.Success) return null; //now that we have the attachment IDs let's request the atthacments and save them to disk ItemType MsgItem = ((ItemInfoResponseMessageType)girt.ResponseMessages.Items[0]).Items.Items[0]; AttachmentResponseShapeType arst = null; AttachmentIdType[] aita = null; if (true == MsgItem.HasAttachments) { //create the attachment shape; we want the mime contnet just in case this is an message item so that we can save to disk arst = new AttachmentResponseShapeType(); arst.IncludeMimeContent = true; arst.IncludeMimeContentSpecified = true; //create an array of attachment ids that we want to request aita = new AttachmentIdType[MsgItem.Attachments.Length]; for (int i = 0; i < MsgItem.Attachments.Length; i++) { aita[i] = new AttachmentIdType(); aita[i].Id = MsgItem.Attachments[i].AttachmentId.Id; } } //create a GetAttachment object for the GetAttachment operation GetAttachmentType gat = new GetAttachmentType(); gat.AttachmentIds = aita; gat.AttachmentShape = arst; GetAttachmentResponseType gart = _esb.GetAttachment(gat); List attachs = new List(); string ext = string.Empty; string savePath = string.Empty; //save each attachment to disk foreach (AttachmentInfoResponseMessageType Attachment in gart.ResponseMessages.Items) { if (Attachment.Attachments[0].ContentId == null) { switch (Attachment.Attachments[0].GetType().Name) { //attachments can be of type FileAttachmentType or ItemAttachmentType //so we need to figure out which type we have before we manipulate it case "FileAttachmentType": //save to disk FileAttachmentType TheFileAttachment = (FileAttachmentType)Attachment.Attachments[0]; ext = Path.GetExtension(Attachment.Attachments[0].Name); savePath = this._siteid + "/" + Guid.NewGuid().ToString() + ext; using (Stream FileToDisk = new FileStream(this._attachSavePath + savePath, FileMode.Create)) { FileToDisk.Write(TheFileAttachment.Content, 0, TheFileAttachment.Content.Length); FileToDisk.Flush(); FileToDisk.Close(); COMailAttachment attach = new COMailAttachment(); attach.Name = Attachment.Attachments[0].Name; attach.FileURL = savePath; ; attach.Size = TheFileAttachment.Content.Length; attach.EmailInfoID = mailid; attachs.Add(attach); //mabll.Add(attach); } break; case "ItemAttachmentType": ItemType TheItemAttachment = ((ItemAttachmentType)Attachment.Attachments[0]).Item; ext = Path.GetExtension(Attachment.Attachments[0].Name); savePath = this._siteid + "/" + Guid.NewGuid().ToString() + ext; using (Stream FileToDisk = new FileStream(this._attachSavePath + savePath, FileMode.Create)) { byte[] ContentBytes = System.Convert.FromBase64String(TheItemAttachment.MimeContent.Value); FileToDisk.Write(ContentBytes, 0, ContentBytes.Length); FileToDisk.Flush(); FileToDisk.Close(); COMailAttachment attach = new COMailAttachment(); attach.Name = Attachment.Attachments[0].Name; attach.FileURL = savePath; attach.Size = ContentBytes.Length; attach.EmailInfoID = mailid; attachs.Add(attach); //mabll.Add(attach); } break; default: break; } } } return attachs; } 

     5.其他操作

     ///

/// 设置邮件已读 /// /// /// public bool SetReadStatus(ItemIdType item) { SetItemFieldType setField = new SetItemFieldType(); PathToUnindexedFieldType path = new PathToUnindexedFieldType(); MessageType message = new MessageType(); message.IsRead = true; message.IsReadSpecified = true; setField.Item1 = message; path.FieldURI = UnindexedFieldURIType.messageIsRead; setField.Item = path; ItemChangeType[] updatedItems = new ItemChangeType[1]; updatedItems[0] = new ItemChangeType(); updatedItems[0].Updates = new ItemChangeDescriptionType[1]; updatedItems[0].Updates[0] = setField; ItemChangeDescriptionType[] updates = new ItemChangeDescriptionType[1]; updates[0] = new ItemChangeDescriptionType(); updates[0].Item = path; updatedItems[0].Item = new ItemIdType(); ((ItemIdType)updatedItems[0].Item).Id = item.Id; ((ItemIdType)updatedItems[0].Item).ChangeKey = item.ChangeKey; UpdateItemType request = new UpdateItemType(); request.ItemChanges = updatedItems; request.ConflictResolution = ConflictResolutionType.AutoResolve; request.MessageDisposition = MessageDispositionType.SaveOnly; request.MessageDispositionSpecified = true; UpdateItemResponseType response = _esb.UpdateItem(request); return response.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Success; } /// /// 删除一封邮件 /// /// /// public bool DeleteMail(ItemIdType item) { // 删除当前邮件 DeleteItemType deleteItem = new DeleteItemType(); deleteItem.ItemIds = new BaseItemIdType[1]; deleteItem.ItemIds[0] = item; // 执行删除 DeleteItemResponseType deleteResponse = _esb.DeleteItem(deleteItem); return deleteResponse.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Success; } //获取收件箱邮件数量 public int GetInBoxTotalCount() { FindItemType findRequest = new FindItemType(); findRequest.ItemShape = new ItemResponseShapeType(); findRequest.ItemShape.BaseShape = DefaultShapeNamesType.IdOnly; DistinguishedFolderIdType folder = new DistinguishedFolderIdType(); folder.Id = DistinguishedFolderIdNameType.inbox; findRequest.ParentFolderIds = new BaseFolderIdType[] { folder }; findRequest.Traversal = ItemQueryTraversalType.Shallow; // Perform the inbox search FindItemResponseType response = _esb.FindItem(findRequest); FindItemResponseMessageType responseMessage = response.ResponseMessages.Items[0] as FindItemResponseMessageType; if (responseMessage.ResponseCode != ResponseCodeType.NoError) { throw new Exception(responseMessage.MessageText); } else { if (responseMessage != null && responseMessage.RootFolder != null) { return responseMessage.RootFolder.TotalItemsInView; } else { return 0; } } } //获取收件箱未读邮件数量 public int GetInBoxUnReadCount() { int unReadCount = 0; FolderResponseShapeType properties = new FolderResponseShapeType(); PathToUnindexedFieldType ptuft = new PathToUnindexedFieldType(); ptuft.FieldURI = UnindexedFieldURIType.folderManagedFolderInformation; PathToUnindexedFieldType[] ptufts = new PathToUnindexedFieldType[1] { ptuft }; properties.AdditionalProperties = ptufts; properties.BaseShape = DefaultShapeNamesType.AllProperties; // Form the get folder request. DistinguishedFolderIdType folder = new DistinguishedFolderIdType(); folder.Id = DistinguishedFolderIdNameType.inbox; GetFolderType request = new GetFolderType(); request.FolderIds = new BaseFolderIdType[1] { folder }; request.FolderShape = properties; // Send the request and get the response. GetFolderResponseType response = _esb.GetFolder(request); ArrayOfResponseMessagesType aormt = response.ResponseMessages; ResponseMessageType[] rmta = aormt.Items; foreach (ResponseMessageType rmt in rmta) { if (rmt.ResponseClass == ResponseClassType.Error) { throw new Exception(rmt.MessageText); } else { FolderInfoResponseMessageType firmt; firmt = (rmt as FolderInfoResponseMessageType); BaseFolderType[] folders = firmt.Folders; foreach (BaseFolderType rfolder in folders) { if (rfolder is FolderType) { FolderType myFolder; myFolder = (rfolder as FolderType); if (myFolder.UnreadCountSpecified) { unReadCount = myFolder.UnreadCount; } } } } } return unReadCount; } /// /// 获取最近发件箱内容 /// /// 发送日期 /// 收件人 /// public ItemType[] GetLastSendItems(DateTime startDate, string recipient) { DistinguishedFolderIdType fita = new DistinguishedFolderIdType(); fita.Id = DistinguishedFolderIdNameType.sentitems; //request AllProperties PathToUnindexedFieldType[] ptufta = new PathToUnindexedFieldType[1]; ptufta[0] = new PathToUnindexedFieldType(); ptufta[0].FieldURI = UnindexedFieldURIType.itemItemClass; ItemResponseShapeType irst = new ItemResponseShapeType(); irst.BaseShape = DefaultShapeNamesType.AllProperties; irst.IncludeMimeContent = false; irst.AdditionalProperties = ptufta; //restrict the returned items to just items of a specific message class PathToUnindexedFieldType MsgClassField = new PathToUnindexedFieldType(); MsgClassField.FieldURI = UnindexedFieldURIType.itemItemClass; ConstantValueType MsgClassToGet = new ConstantValueType(); MsgClassToGet.Value = "IPM.NOTE"; FieldURIOrConstantType MsgClassConstant = new FieldURIOrConstantType(); MsgClassConstant.Item = MsgClassToGet; IsEqualToType iett = new IsEqualToType(); iett.FieldURIOrConstant = MsgClassConstant; iett.Item = MsgClassField; //restrict the returned items greater than a specified date PathToUnindexedFieldType StartDateReceivedField = new PathToUnindexedFieldType(); StartDateReceivedField.FieldURI = UnindexedFieldURIType.itemDateTimeReceived; ConstantValueType StartDateReceivedToGet = new ConstantValueType(); StartDateReceivedToGet.Value = startDate.ToUniversalTime().ToString(); FieldURIOrConstantType StartDateReceivedConstant = new FieldURIOrConstantType(); StartDateReceivedConstant.Item = StartDateReceivedToGet; IsGreaterThanOrEqualToType igtett = new IsGreaterThanOrEqualToType(); igtett.FieldURIOrConstant = StartDateReceivedConstant; igtett.Item = StartDateReceivedField; //restrict the return items' Recipient PathToUnindexedFieldType recipientField = new PathToUnindexedFieldType(); recipientField.FieldURI = UnindexedFieldURIType.messageToRecipients; ContainsExpressionType ceContainsType = new ContainsExpressionType(); ceContainsType.Constant = new ConstantValueType(); ceContainsType.Constant.Value = recipient; ceContainsType.ContainmentComparison = ContainmentComparisonType.IgnoreCase; ceContainsType.ContainmentComparisonSpecified = true; ceContainsType.ContainmentMode = ContainmentModeType.Substring; ceContainsType.ContainmentModeSpecified = true; ceContainsType.Item = recipientField; AndType at = new AndType(); at.Items = new SearchExpressionType[3]; at.Items[0] = igtett; at.Items[1] = ceContainsType; //TODO: Uncomment the following line if you want to display only email items from folder // If the following line is commented then all items would be returned from folder, // for e.g. Reports, Appointment, Meeting Requests, Contacts etc. at.Items[2] = iett; RestrictionType rt = new RestrictionType(); rt.Item = at; //find the items FindItemType fit = new FindItemType(); fit.ItemShape = irst; fit.ParentFolderIds = new BaseFolderIdType[]{fita}; fit.Restriction = rt; FindItemResponseType firt = this._esb.FindItem(fit); return ((ArrayOfRealItemsType)((FindItemResponseMessageType)firt.ResponseMessages.Items[0]).RootFolder.Item).Items; } 

 

 

你可能感兴趣的:(EWS)