通过exchange web service收发邮件
?? ?最近做通過ews收發(fā)exchange郵件,又有不小收獲,下面說下遇到的問題及解決辦法
?? ?主要是用ExchangeServiceBinding來進(jìn)行郵件操作
?? ?1.exchange服務(wù)器安全證書,就是用于測試的exchange服務(wù)器的證書不被信任,由于是測試當(dāng)然沒有申請合適的證書,然后ews會驗(yàn)證服務(wù)器的證書,所以報(bào)錯(cuò),解決方法:
?? ?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.發(fā)送郵件,不帶附件
?? ? /// <summary>/// 發(fā)送郵件/// </summary>/// <param name="mail">郵件實(shí)體信息</param>/// <returns></returns>public bool SendMail(COEmailInfo mail){// Create the CreateItem request.CreateItemType createItemRequest = new CreateItemType();// Specifiy how the created items are handledcreateItemRequest.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.發(fā)送郵件,帶附件,這里需要注意,如果是大附件的話,首先要exchange那邊設(shè)置附件大小,然后是設(shè)置ews服務(wù)的http超時(shí)(iis),默認(rèn)是120s,如果網(wǎng)速不行傳輸時(shí)間大于120還是會報(bào)錯(cuò),主要是因?yàn)閔ttp傳輸,帶附件的郵件分3步,一是發(fā)郵件到草稿箱,二是給剛才的郵件添加附件,三是發(fā)送剛才草稿箱的郵件。
?
?? ? /// <summary>/// 發(fā)送帶附件的郵件/// </summary>/// <param name="mail">郵件實(shí)體</param>/// <param name="attachments">附件列表</param>/// <returns></returns>public bool SendMailWithAttachments(COEmailInfo mail, List<COMailAttachment> 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<COMailAttachment> 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;}//創(chuàng)建草稿箱郵件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;}//發(fā)送草稿箱郵件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);}}?
?? ?發(fā)送帶回執(zhí)的郵件只需在發(fā)送郵件時(shí)指明message的IsReadReceiptRequested和IsReadReceiptRequestedSpecified屬性為true
?? ?4.收郵件,主要是注意郵件的內(nèi)聯(lián)附件
?? ? /// <summary>/// 獲取指定文件夾的郵件/// </summary>/// <param name="type">文件夾類型</param>/// <param name="isUnReadOnly">是否只下載已讀</param>/// <returns></returns>public COEmailInfo[] GetMails(DistinguishedFolderIdNameType type, bool isUnReadOnly, List<COMailAttachment> 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 messagesif (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 messagesisEqTo.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<COEmailInfo> mails = new List<COEmailInfo>();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 = "無標(biāo)題";}if (myMessage.Body.BodyType1 == BodyTypeType.Text){mail.StraightMatter = myMessage.Body.Value.Replace(Environment.NewLine, "<br />");}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){//+8mail.CreateTime = myMessage.DateTimeReceived.AddHours(8);}//mail.ID = mibll.Add(mail);List<COMailAttachment> 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();}/// <summary>/// 獲取對應(yīng)的內(nèi)聯(lián)附件/// </summary>/// <param name="msg">郵件</param>/// <param name="body">郵件正文</param>/// <returns></returns>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.gif (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 diskarst = new AttachmentResponseShapeType();arst.IncludeMimeContent = true;arst.IncludeMimeContentSpecified = true;//create an array of attachment ids that we want to requestaita = new AttachmentIdType[1];aita[0] = new AttachmentIdType();aita[0].Id = attach.AttachmentId.Id;//create a GetAttachment object for the GetAttachment operationGetAttachmentType 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 diskforeach (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 itcase "FileAttachmentType"://save to diskFileAttachmentType 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;}/// <summary>/// 下載某個(gè)郵件的附件/// </summary>/// <param name="iit">郵件</param>/// <returns></returns>public List<COMailAttachment> 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 retrievePathToUnindexedFieldType[] 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 itemsGetItemType 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 diskItemType 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 diskarst = new AttachmentResponseShapeType();arst.IncludeMimeContent = true;arst.IncludeMimeContentSpecified = true;//create an array of attachment ids that we want to requestaita = 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 operationGetAttachmentType gat = new GetAttachmentType();gat.AttachmentIds = aita;gat.AttachmentShape = arst;GetAttachmentResponseType gart = _esb.GetAttachment(gat);List<COMailAttachment> attachs = new List<COMailAttachment>();string ext = string.Empty;string savePath = string.Empty;//save each attachment to diskforeach (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 itcase "FileAttachmentType"://save to diskFileAttachmentType 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.其他操作
?? ? /// <summary>/// 設(shè)置郵件已讀/// </summary>/// <param name="item"></param>/// <returns></returns>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;}/// <summary>/// 刪除一封郵件/// </summary>/// <param name="item"></param>/// <returns></returns>public bool DeleteMail(ItemIdType item){// 刪除當(dāng)前郵件DeleteItemType deleteItem = new DeleteItemType();deleteItem.ItemIds = new BaseItemIdType[1];deleteItem.ItemIds[0] = item;// 執(zhí)行刪除DeleteItemResponseType deleteResponse = _esb.DeleteItem(deleteItem);return deleteResponse.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Success;}//獲取收件箱郵件數(shù)量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 searchFindItemResponseType 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;}}}//獲取收件箱未讀郵件數(shù)量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;}/// <summary>/// 獲取最近發(fā)件箱內(nèi)容/// </summary>/// <param name="startDate">發(fā)送日期</param>/// <param name="recipient">收件人</param>/// <returns></returns>public ItemType[] GetLastSendItems(DateTime startDate, string recipient){DistinguishedFolderIdType fita = new DistinguishedFolderIdType();fita.Id = DistinguishedFolderIdNameType.sentitems;//request AllPropertiesPathToUnindexedFieldType[] 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 classPathToUnindexedFieldType MsgClassField = newPathToUnindexedFieldType();MsgClassField.FieldURI = UnindexedFieldURIType.itemItemClass;ConstantValueType MsgClassToGet = new ConstantValueType();MsgClassToGet.Value = "IPM.NOTE";FieldURIOrConstantType MsgClassConstant = newFieldURIOrConstantType();MsgClassConstant.Item = MsgClassToGet;IsEqualToType iett = new IsEqualToType();iett.FieldURIOrConstant = MsgClassConstant;iett.Item = MsgClassField;//restrict the returned items greater than a specified datePathToUnindexedFieldType 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' RecipientPathToUnindexedFieldType 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 itemsFindItemType 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;}?
?
?
總結(jié)
以上是生活随笔為你收集整理的通过exchange web service收发邮件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 日常报错 TypeError: Cann
- 下一篇: 《那些年啊,那些事——一个程序员的奋斗史