private static void GetAllMessageEmail(Collection <ItemId> itemIds) { if (itemIds == null || itemIds.Count == 0) { return; } exchangeSecretarReport = new List <EmailMessage>(); PropertySet propertySet = new PropertySet(EmailMessageSchema.Subject, EmailMessageSchema.ToRecipients, EmailMessageSchema.IsRead, EmailMessageSchema.Sender, EmailMessageSchema.TextBody, EmailMessageSchema.Body, EmailMessageSchema.DateTimeSent); ServiceResponseCollection <GetItemResponse> responses = exchangeService.BindToItems(itemIds, propertySet); foreach (GetItemResponse getItemResponse in responses) { try { Item item = getItemResponse.Item; EmailMessage message = (EmailMessage)item; exchangeSecretarReport.Add(message); //Console.WriteLine("Found item {0}.", message.Id.ToString().Substring(144)); } catch (Exception ex) { //Console.WriteLine("Exception while getting a message: {0}", ex.Message); } } if (responses.OverallResult == ServiceResult.Success) { //Console.WriteLine("All email messages retrieved successfully."); //Console.WriteLine("\r\n"); } }
public IEnumerable <MailItem> GetMailFrom(WellKnownFolderName folderName, int maxItems) { var view = new ItemView(maxItems) { Traversal = ItemTraversal.Shallow, }; FindItemsResults <Item> findResults = service.FindItems(folderName, view); if (findResults.Count() > 0) { var itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.From, EmailMessageSchema.ToRecipients, ItemSchema.Attachments) { RequestedBodyType = BodyType.Text }; ServiceResponseCollection <GetItemResponse> items = service.BindToItems(findResults.Select(item => item.Id), itempropertyset); foreach (var item in items) { var emailMessage = item.Item as EmailMessage; var mailItem = MailItem.FromExchangeMailMessage(emailMessage); yield return(mailItem); } } }
/// <summary> /// Dump the properties from the given PropertySet of every item in the /// ItemId list to XML files. /// </summary> /// <param name="itemIds">List of ItemIds to get</param> /// <param name="propertySet">PropertySet to use when getting items</param> /// <param name="destinationFolderPath">Folder to save messages to</param> /// <param name="service">ExchangeService to use to make EWS calls</param> public static void DumpXML( List <ItemId> itemIds, PropertySet propertySet, string destinationFolderPath, ExchangeService service) { DebugLog.WriteVerbose(String.Format("Getting {0} items by ItemId.", itemIds.Count)); service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. ServiceResponseCollection <GetItemResponse> responses = service.BindToItems(itemIds, propertySet); DebugLog.WriteVerbose("Finished getting items."); DebugLog.WriteVerbose("Started writing XML dumps to files."); foreach (GetItemResponse response in responses) { switch (response.Result) { case ServiceResult.Success: DumpXML(response.Item, destinationFolderPath); break; case ServiceResult.Error: DumpErrorResponseXML(response, destinationFolderPath); break; case ServiceResult.Warning: throw new NotImplementedException("DumpXML doesn't handle ServiceResult.Warning."); default: throw new NotImplementedException("Unexpected ServiceResult."); } } DebugLog.WriteVerbose("Finished writing XML dumps to files."); }
private Attachment[] GetAttachmentsWithManagedApi(string[] attachmentIds, string authToken, string ewsUrl) { ExchangeService service = new ExchangeService(); service.Credentials = new OAuthCredentials(authToken); service.Url = new Uri(ewsUrl); ServiceResponseCollection <GetAttachmentResponse> responses = service.GetAttachments( attachmentIds, null, new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.MimeContent)); List <Attachment> attachments = new List <Attachment>(); foreach (GetAttachmentResponse response in responses) { Attachment attachment = new Attachment(); attachment.AttachmentName = response.Attachment.Name; if (response.Attachment is FileAttachment) { FileAttachment file = response.Attachment as FileAttachment; attachment.AttachmentBytes = file.Content; } else if (response.Attachment is ItemAttachment) { // Skip item attachments for now // TODO: Add code to extract the MIME content of the item // and build a .EML file to save to OneDrive. } attachments.Add(attachment); } return(attachments.ToArray()); }
private void btnDeleteMail_Click(object sender, EventArgs e) { if (this.listViewMail.Visible && this.listViewMail.SelectedItems.Count > 0) { List <ItemId> deletedMailId = new List <ItemId>(); foreach (ListViewItem id in this.listViewMail.SelectedItems) { ItemId itemId = new ItemId(id.SubItems[4].Text); deletedMailId.Add(itemId); } if (deletedMailId.Count > 0) { ServiceResponseCollection <ServiceResponse> response = service.DeleteItems(deletedMailId, DeleteMode.MoveToDeletedItems, SendCancellationsMode.SendOnlyToAll, AffectedTaskOccurrence.SpecifiedOccurrenceOnly); this.txtLog.Text = "Delete mail success\r\nEWS API: DeleteItems\r\nLocation:..\\EWS\\EWS\\Form1.cs(274)\r\n\r\n"; getMails(null, null); } } else { MessageBox.Show("Select a mail firstly"); initialMailListView(); return; } }
public void linkEmails() { FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(128)); if (findResults.TotalCount > 0) { ServiceResponseCollection <GetItemResponse> items = service.BindToItems(findResults.Select(item => item.Id), new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.From, EmailMessageSchema.ToRecipients)); foreach (GetItemResponse i in items) { MailItem m = new MailItem(); Item it = i.Item; m.From = ((Microsoft.Exchange.WebServices.Data.EmailAddress)it[EmailMessageSchema.From]).Address; m.Recipients = ((Microsoft.Exchange.WebServices.Data.EmailAddressCollection)it[EmailMessageSchema.ToRecipients]).Select(r => r.Address).ToArray(); m.Subject = it.Subject; m.Body = it.Body.Text; m.Recieved = it.DateTimeReceived; m.attachments = it.Attachments; foreach (Attachment a in m.attachments) { this.uploadAttachments(a); } i.Item.Delete(DeleteMode.HardDelete); } } }
} // End Sub FindUnreadEmail public static void MoveMessage(ExchangeService service) { // Create two items to be moved. You can move any item type in your Exchange mailbox. // You will need to save these items to your Exchange mailbox before they can be moved. EmailMessage email1 = new EmailMessage(service); email1.Subject = "Draft email one"; email1.Body = new MessageBody(BodyType.Text, "Draft body of the mail."); EmailMessage email2 = new EmailMessage(service); email2.Subject = "Draft email two"; email1.Body = new MessageBody(BodyType.Text, "Draft body of the mail."); System.Collections.ObjectModel.Collection <EmailMessage> messages = new System.Collections.ObjectModel.Collection <EmailMessage>(); messages.Add(email1); messages.Add(email2); try { // This results in a CreateItem operation call to EWS. The items are created on the server. // The response contains the item identifiers of the newly created items. The items on the client // now have item identifiers, which you need in order to move the item. ServiceResponseCollection <ServiceResponse> responses = service.CreateItems(messages, WellKnownFolderName.Drafts, MessageDisposition.SaveOnly, null); if (responses.OverallResult == ServiceResult.Success) { System.Console.WriteLine("Successfully created items to be copied."); } else { throw new System.Exception("The batch creation of the email message draft items was not successful."); } } catch (ServiceResponseException ex) { System.Console.WriteLine("Error: {0}", ex.Message); } try { // You can move a single item. This will result in a MoveItem operation call to EWS. // The EmailMessage that is returned is the item with its updated item identifier. You must save the email // message to the server before you can move it. EmailMessage email3 = email1.Move(WellKnownFolderName.DeletedItems) as EmailMessage; } catch (ServiceResponseException ex) { System.Console.WriteLine("Error: {0}", ex.Message); } } // End Sub MoveMessage
/// <summary> /// Copies a single item between folders in a call to EWS. /// </summary> /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param> private static void CopyAnItem(ExchangeService service) { // Create two items to copy. You can copy any item type in your Exchange mailbox. // You will need to save these items to your Exchange mailbox before they can be copied. EmailMessage email1 = new EmailMessage(service); email1.Subject = "Draft email one"; email1.Body = new MessageBody(BodyType.Text, "Draft body of the mail."); EmailMessage email2 = new EmailMessage(service); email2.Subject = "Draft email two"; email1.Body = new MessageBody(BodyType.Text, "Draft body of the mail."); Collection <EmailMessage> messages = new Collection <EmailMessage>(); messages.Add(email1); messages.Add(email2); try { // This results in a CreateItem operation call to EWS. The items are created on the server. // The response contains the item identifiers of the newly created items. The items on the client // now have item identifiers, which you need in order to make a copy. ServiceResponseCollection <ServiceResponse> responses = service.CreateItems(messages, WellKnownFolderName.Drafts, MessageDisposition.SaveOnly, null); if (responses.OverallResult == ServiceResult.Success) { Console.WriteLine("Successfully created items that we will copy."); } else { throw new Exception("The batch creation of the email message draft items was not successful."); } } catch (ServiceResponseException ex) { Console.WriteLine("Error: {0}", ex.Message); } try { // You can create copies of a single item. This will result in a CopyItem operation call to EWS. // The EmailMessage that is returned is a copy of the item with its own unique identifier. The email message to copy // must be saved on the server before you can copy it. EmailMessage email3 = email1.Copy(WellKnownFolderName.DeletedItems) as EmailMessage; } catch (ServiceResponseException ex) { Console.WriteLine("Error: {0}", ex.Message); } }
/// <summary> /// Deletes a single item in a call to EWS. /// </summary> /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param> private static void DeleteAnItem(ExchangeService service) { // Create an item to be deleted. You can delete any item type in your Exchange mailbox. // You will need to save these items to your Exchange mailbox before they can be deleted. EmailMessage email1 = new EmailMessage(service); email1.Subject = "Draft email one"; email1.Body = new MessageBody(BodyType.Text, "Draft body of the mail."); EmailMessage email2 = new EmailMessage(service); email2.Subject = "Draft email two"; email1.Body = new MessageBody(BodyType.Text, "Draft body of the mail."); Collection <EmailMessage> messages = new Collection <EmailMessage>(); messages.Add(email1); messages.Add(email2); try { // This results in a CreateItem call to EWS. The items are created on the server. // The response contains the item identifiers of the newly created items. The items on the client // now have item identifiers. You need the identifiers to delete the item. ServiceResponseCollection <ServiceResponse> responses = service.CreateItems(messages, WellKnownFolderName.Drafts, MessageDisposition.SaveOnly, null); if (responses.OverallResult == ServiceResult.Success) { Console.WriteLine("Successfully created items to be copied."); } else { throw new Exception("The batch creation of the email message draft items was not successful."); } } catch (ServiceResponseException ex) { Console.WriteLine("Error: {0}", ex.Message); } try { // You can delete a single item. Both of the following lines will result in a DeleteItem operation call to EWS. // The email message to delete must be saved on the server before you can delete it. email1.Delete(DeleteMode.HardDelete); email2.Delete(DeleteMode.HardDelete); } catch (ServiceResponseException ex) { Console.WriteLine("Error: {0}", ex.Message); } }
/// <summary> /// Get the MimeContent of each Item specified in itemIds and write it /// to a string. /// </summary> /// <param name="itemIds">ItemIds to retrieve</param> /// <param name="destinationFolderPath">Folder to save messages to</param> /// <param name="service">ExchangeService to use to make EWS calls</param> /// <param name="TheMime">MIME string to set</param> public static void DumpMIMEToString( List <ItemId> itemIds, ExchangeService service, ref string TheMime) { DebugLog.WriteVerbose(String.Format("Getting {0} items by ItemId.", itemIds.Count)); string MimeToReturn = string.Empty; PropertySet mimeSet = new PropertySet(BasePropertySet.IdOnly); mimeSet.Add(EmailMessageSchema.MimeContent); mimeSet.Add(EmailMessageSchema.Subject); service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. ServiceResponseCollection <GetItemResponse> responses = service.BindToItems(itemIds, mimeSet); DebugLog.WriteVerbose("Finished getting items."); foreach (GetItemResponse response in responses) { switch (response.Result) { case ServiceResult.Success: if (response.Item.MimeContent == null) { throw new ApplicationException("No MIME content to write"); } UTF8Encoding oUTF8Encoding = new UTF8Encoding(); MimeToReturn = oUTF8Encoding.GetString(response.Item.MimeContent.Content); break; case ServiceResult.Error: MimeToReturn = "ErrorCode: " + response.ErrorCode.ToString() + "\r\n" + "\r\nErrorMessage: " + response.ErrorMessage + "\r\n"; break; case ServiceResult.Warning: throw new NotImplementedException("DumpMIMEToString doesn't handle ServiceResult.Warning."); default: throw new NotImplementedException("DumpMIMEToString encountered an unexpected ServiceResult."); } } TheMime = MimeToReturn; DebugLog.WriteVerbose("Finished dumping MimeContents for each item."); }
public Item GetItem(ItemId itemId) { List <ItemId> items = new List <ItemId>() { itemId }; PropertySet properties = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.Body, EmailMessageSchema.Sender, EmailMessageSchema.Subject); properties.RequestedBodyType = BodyType.Text; ServiceResponseCollection <GetItemResponse> response = _service.BindToItems(items, properties); return(response[0].Item); }
private static void ArchiveItemsInFolder(ExchangeService service) { // Get the item IDs of the individual items to archive. // Create a search filter. List <SearchFilter> searchFilterCollection = new List <SearchFilter>(); searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, "Contoso")); SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection); // create an item view with the properties to return. ItemView view = new ItemView(50); view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject); view.Traversal = ItemTraversal.Shallow; // Get item IDs for the items in your Inbox with "Contoso" in the subject. FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, view); List <ItemId> itemIds = new List <ItemId>(); foreach (Item item in findResults) { itemIds.Add(item.Id); } // Archive the items that match your search. ServiceResponseCollection <ArchiveItemResponse> archivedItems = service.ArchiveItems(itemIds, WellKnownFolderName.Inbox); // Note that archiving must be enabled for the target user or archiving will fail. if (archivedItems.OverallResult != ServiceResult.Success) { // Display any errors. foreach (ArchiveItemResponse response in archivedItems) { if (response.ErrorCode != ServiceError.NoError) { Console.WriteLine("Error message for item " + "{0}: " + "{1}", response.Item, response.ErrorMessage); } } } else // Display the number of items archived. { Console.WriteLine("{0}" + " items archived.", archivedItems.Count); } }
//itemId 转mailMessage public static List <EmailMessage> BatchGetEmailIlems(ExchangeService service, Collection <ItemId> itemid) { //绑定属性 PropertySet propertySet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.InternetMessageId, //Message Id EmailMessageSchema.InternetMessageHeaders, //Message Hesder EmailMessageSchema.HasAttachments, EmailMessageSchema.Attachments, EmailMessageSchema.ConversationIndex, //Thread-Inder EmailMessageSchema.ConversationTopic, //Thread-Topic EmailMessageSchema.From, //From EmailMessageSchema.ToRecipients, //To EmailMessageSchema.CcRecipients, //Cc EmailMessageSchema.ReplyTo, //ReplayTo EmailMessageSchema.InReplyTo, //In-Replay-To EmailMessageSchema.References, //References EmailMessageSchema.Subject, //Subject EmailMessageSchema.TextBody, EmailMessageSchema.Attachments, EmailMessageSchema.DateTimeSent, //Sent Date EmailMessageSchema.DateTimeReceived, //Received Date EmailMessageSchema.Sender, EmailMessageSchema.MimeContent, //导出到eml文件 EmailMessageSchema.IsRead, EmailMessageSchema.EffectiveRights, EmailMessageSchema.ReceivedBy); //邮件已读状态 ServiceResponseCollection <GetItemResponse> respone = service.BindToItems(itemid, propertySet); List <EmailMessage> messageItems = new List <EmailMessage>(); foreach (GetItemResponse getItemRespone in respone) { try { Item item = getItemRespone.Item; EmailMessage message = (EmailMessage)item; messageItems.Add(message); } catch (Exception ex) { // Console.WriteLine("Exception with getting a message:{0}", ex.Message); throw; } } return(messageItems); }
public static void BatchDeleteDeletedItems(ExchangeService service, Collection <ItemId> itemIds) { // Delete the batch of email message objects. // This method call results in an DeleteItem call to EWS. ServiceResponseCollection <ServiceResponse> response = service.DeleteItems(itemIds, DeleteMode.HardDelete, null, AffectedTaskOccurrence.AllOccurrences); // Check for success of the DeleteItems method call. // DeleteItems returns success even if it does not find all the item IDs. if (response.OverallResult == ServiceResult.Success) { Console.WriteLine("Email messages deleted successfully.\r\n"); } // If the method did not return success, print a message. else { Console.WriteLine("Not all email messages deleted successfully.\r\n"); } }
/// <summary> /// Get the MimeContent of each Item specified in itemIds and write it /// to the destination folder. /// </summary> /// <param name="itemIds">ItemIds to retrieve</param> /// <param name="destinationFolderPath">Folder to save messages to</param> /// <param name="service">ExchangeService to use to make EWS calls</param> public static void DumpMIME( List <ItemId> itemIds, string destinationFolderPath, ExchangeService service) { DebugLog.WriteVerbose(String.Format("Getting {0} items by ItemId.", itemIds.Count)); PropertySet mimeSet = new PropertySet(BasePropertySet.IdOnly); mimeSet.Add(EmailMessageSchema.MimeContent); mimeSet.Add(EmailMessageSchema.Subject); //mimeSet.Add(AppointmentSchema.MimeContent); //mimeSet.Add(AppointmentSchema.Subject); //mimeSet.Add(AppointmentSchema.RequiredAttendees); //mimeSet.Add(AppointmentSchema.OptionalAttendees); service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. ServiceResponseCollection <GetItemResponse> responses = service.BindToItems(itemIds, mimeSet); DebugLog.WriteVerbose("Finished getting items."); foreach (GetItemResponse response in responses) { switch (response.Result) { case ServiceResult.Success: DumpMIME(response.Item, destinationFolderPath); break; case ServiceResult.Error: DumpErrorResponseXML(response, destinationFolderPath); break; case ServiceResult.Warning: throw new NotImplementedException("DumpMIME doesn't handle ServiceResult.Warning."); default: throw new NotImplementedException("DumpMIME encountered an unexpected ServiceResult."); } } DebugLog.WriteVerbose("Finished dumping MimeContents for each item."); }
/// <summary> /// Reads response elements from XML. /// </summary> /// <param name="reader">The reader.</param> internal override void ReadElementsFromXml(EwsServiceXmlReader reader) { responseCollection = new ServiceResponseCollection<MailTipsResponseMessage>(); base.ReadElementsFromXml(reader); reader.ReadStartElement(XmlNamespace.Messages, XmlElementNames.ResponseMessages); if (!reader.IsEmptyElement) { // Because we don't have count of returned objects // test the element to determine if it is return object or EndElement reader.Read(); while (reader.IsStartElement(XmlNamespace.Messages, XmlElementNames.MailTipsResponseMessageType)) { MailTipsResponseMessage mrm = new MailTipsResponseMessage(); mrm.LoadFromXml(reader, XmlElementNames.MailTipsResponseMessageType); this.responseCollection.Add(mrm); reader.Read(); } reader.EnsureCurrentNodeIsEndElement(XmlNamespace.Messages, XmlElementNames.ResponseMessages); } }
/// <summary> /// Reads response elements from XML. /// </summary> /// <param name="reader">The reader.</param> internal override void ReadElementsFromXml(EwsServiceXmlReader reader) { responseCollection = new ServiceResponseCollection <MailTipsResponseMessage>(); base.ReadElementsFromXml(reader); reader.ReadStartElement(XmlNamespace.Messages, XmlElementNames.ResponseMessages); if (!reader.IsEmptyElement) { // Because we don't have count of returned objects // test the element to determine if it is return object or EndElement reader.Read(); while (reader.IsStartElement(XmlNamespace.Messages, XmlElementNames.MailTipsResponseMessageType)) { MailTipsResponseMessage mrm = new MailTipsResponseMessage(); mrm.LoadFromXml(reader, XmlElementNames.MailTipsResponseMessageType); this.responseCollection.Add(mrm); reader.Read(); } reader.EnsureCurrentNodeIsEndElement(XmlNamespace.Messages, XmlElementNames.ResponseMessages); } }
/// <summary> /// Check on mail folder last received asuntos /// </summary> /// <param name="prmLastDateTimeChecked">Last date registered of check to filter folder</param> /// <returns></returns> public List <Entidades.Asunto> GetLastAsuntosAdded(DateTime prmLastDateTimeChecked) { // Generate a new asunto list to return List <Entidades.Asunto> lstAsuntoToProcess = new List <Entidades.Asunto>(); // Get filtering properties for search on inbox SearchFilter filterCriteria = getFilterForAsuntosSearch(prmLastDateTimeChecked.AddSeconds(10)); // Get view with specify properties for search ItemView viewContainer = getResultViewForAsuntoList(); // Generate a collection for matching items FindItemsResults <Item> resultOfSearch = mailServiceConnection.FindItems(asuntoFolder, filterCriteria, viewContainer); if (resultOfSearch.TotalCount > 0) { // Generate a new ServiceResponseCollection with items saved ServiceResponseCollection <GetItemResponse> itemWithBodyAndDateReceived = mailServiceConnection.BindToItems(resultOfSearch.Select(item => item.Id), new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.DateTimeReceived)); // Iterates over all results finded foreach (var item in itemWithBodyAndDateReceived.Select(item => item.Item).ToArray()) { // Save temporaly in a variable subject result string subjectWithAsunto = item.Subject; // Get Start point for cutting string resullt int intStartCutString = subjectWithAsunto.IndexOf(startSubstringCut) + startSubstringCut.Length; int intEndCutString = subjectWithAsunto.LastIndexOf(endSubstringCut); // With end and start can obtain asunto number string asuntoNumber = subjectWithAsunto.Substring(intStartCutString, (intEndCutString - intStartCutString)); string shortDescription = getShortDescriptionByFiltering(item.Body); // Generate a new entidades of asunto and add to list lstAsuntoToProcess.Add(new Entidades.Asunto() { Numero = asuntoNumber, DescripcionBreve = shortDescription, LoadedOnSolucionameDate = item.DateTimeReceived }); } } // Return processed list return(lstAsuntoToProcess); }
private void btnDeleteMeeting_Click(object sender, EventArgs e) { initialMeetingList(); List <ItemId> deletedMeetingId = new List <ItemId>(); if (this.listViewMeeting.SelectedItems.Count == 0) { MessageBox.Show("Select a mail firstly"); return; } foreach (ListViewItem id in this.listViewMeeting.SelectedItems) { ItemId itemId = new ItemId(id.SubItems[0].Text); deletedMeetingId.Add(itemId); } if (deletedMeetingId.Count > 0) { ServiceResponseCollection <ServiceResponse> response = service.DeleteItems(deletedMeetingId, DeleteMode.MoveToDeletedItems, SendCancellationsMode.SendOnlyToAll, AffectedTaskOccurrence.SpecifiedOccurrenceOnly); this.txtLog.Text = "Delete meeting success\r\nEWS API: DeleteItems\r\nLocation:..\\EWS\\EWS\\Form1.cs(274)\r\n\r\n"; this.btnGetMeetingList_Click(sender, e); } }
object ParseResponse(EwsServiceXmlReader reader) { ServiceResponseCollection <SearchMailboxesResponse> serviceResponses = new ServiceResponseCollection <SearchMailboxesResponse>(); reader.ReadStartElement(XmlNamespace.Messages, XmlElementNames.ResponseMessages); while (true) { // Read ahead to see if we've reached the end of the response messages early. reader.Read(); if (reader.IsEndElement(XmlNamespace.Messages, XmlElementNames.ResponseMessages)) { break; } SearchMailboxesResponse response = new SearchMailboxesResponse(); response.LoadFromXml(reader, this.GetResponseMessageXmlElementName()); serviceResponses.Add(response); } reader.ReadEndElementIfNecessary(XmlNamespace.Messages, XmlElementNames.ResponseMessages); return(serviceResponses); }
static private void GetExchangeSecretarReport() { SpeechSynthesizer speech = new SpeechSynthesizer(); speech.SetOutputToDefaultAudioDevice(); GetAllMessageEmail(itemIds); if (exchangeSecretarReport == null || exchangeSecretarReport.Count == 0) { return; } foreach (EmailMessage item in exchangeSecretarReport) { foreach (var it in keyWords) { if (item.TextBody.Text.Contains(it)) { speech.Speak("Уважаемый Алексей Романович вам пришла почта от " + item.Sender.Name + "в письме написано: " + item.TextBody.Text); Collection <ItemId> bufferFoDeleted = new Collection <ItemId>(); bufferFoDeleted.Add(item.Id); ServiceResponseCollection <ServiceResponse> response = exchangeService.DeleteItems(bufferFoDeleted, DeleteMode.SoftDelete, null, AffectedTaskOccurrence.AllOccurrences); if (response.OverallResult == ServiceResult.Success) { speech.Speak("Письмо прочтено!"); if (exchangeSecretarReport == null || exchangeSecretarReport.Count == 0) { return; } } else { speech.Speak("Письмо прочтено! Но результат о прочтении записать не удалось"); } } } } }
public static void DeleteItems(List <string> lstDeleteItems) { try { if (_globalService == null) { _globalService = GetExchangeServiceObject(new TraceListner()); } if (!_globalService.HttpHeaders.ContainsKey("X-AnchorMailbox")) { _globalService.HttpHeaders.Add("X-AnchorMailbox", User); } else { _globalService.HttpHeaders["X-AnchorMailbox"] = User; } _globalService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, User); Collection <ItemId> itemIds = new Collection <ItemId>(); List <int> lstNotFound = new List <int>(); foreach (string strId in lstDeleteItems) { try { Item _item = Item.Bind(_globalService, new ItemId(strId), PropertySet.IdOnly); if (_item != null) { itemIds.Add(_item.Id); } } catch (ServiceResponseException ex) { if (ex.ErrorCode == ServiceError.ErrorItemNotFound) // item not found { WriteLog("Item is not found " + strId); } else { WriteLog("Error " + ex.ErrorCode.ToString()); } } catch (Exception ex) { WriteLog(ex.Message); } } IEnumerable <IEnumerable <ItemId> > batchedList = itemIds.Batch(500); int count = 0; if (batchedList.Any()) { StringBuilder sbErrorMsgs = new StringBuilder(); List <ServiceError> lstError = new List <ServiceError>(); foreach (IEnumerable <ItemId> batch_Items in batchedList) { var batchItems = batch_Items as ItemId[] ?? batch_Items.ToArray(); if (batchItems.Any()) { ServiceResponseCollection <ServiceResponse> responses = _globalService.DeleteItems( batchItems, DeleteMode.HardDelete, SendCancellationsMode.SendToNone, AffectedTaskOccurrence.AllOccurrences); if (responses.OverallResult == ServiceResult.Success) { count++; } foreach (ServiceResponse resp in responses) { if (resp.Result != ServiceResult.Success) { if (!lstError.Contains(resp.ErrorCode)) { sbErrorMsgs.Append(string.Format("\r\n{0}: {1}", "ResultText", resp.Result)); sbErrorMsgs.Append(string.Format("\r\n{0}: {1}", "ErrorCodeText", resp.ErrorCode)); sbErrorMsgs.Append(string.Format("\r\n{0}: {1}", "ErrorMessageText", resp.ErrorMessage)); lstError.Add(resp.ErrorCode); } } } } } if (!string.IsNullOrEmpty(sbErrorMsgs.ToString())) { WriteLog(sbErrorMsgs.ToString()); } } } catch (Exception e) { WriteLog(e.Message); } }
/// <summary> /// /// </summary> /// <returns></returns> public static ObservableCollection <ExchangeData> GetUserAppointments() { ObservableCollection <ExchangeData> lstData = new ObservableCollection <ExchangeData>(); try { if (_globalService == null) { _globalService = GetExchangeServiceObject(new TraceListner()); } if (!_globalService.HttpHeaders.ContainsKey("X-AnchorMailbox")) { _globalService.HttpHeaders.Add("X-AnchorMailbox", User); } else { _globalService.HttpHeaders["X-AnchorMailbox"] = User; } _globalService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, User); // AppointmentSchema.Id PropertySet basicProps = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Start, AppointmentSchema.ICalUid, ItemSchema.Subject, ItemSchema.Id, AppointmentSchema.Organizer, ItemSchema.Categories); DateTime dtStart = DateTime.Now.AddDays(BackDays); CalendarView calView = new CalendarView(dtStart, dtStart.AddYears(2)) { Traversal = ItemTraversal.Shallow, PropertySet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Start), MaxItemsReturned = 500 }; List <Appointment> appointments = new List <Appointment>(); FindItemsResults <Appointment> userAppointments = _globalService.FindAppointments(WellKnownFolderName.Calendar, calView); if ((userAppointments != null) && (userAppointments.Any())) { appointments.AddRange(userAppointments); while (userAppointments.MoreAvailable) { calView.StartDate = appointments.Last().Start; userAppointments = _globalService.FindAppointments(WellKnownFolderName.Calendar, calView); appointments.AddRange(userAppointments); } ServiceResponseCollection <ServiceResponse> response = _globalService.LoadPropertiesForItems(appointments, basicProps); if (response.OverallResult != ServiceResult.Success) // property load not success { return(null); } if (appointments?.Count > 0) { foreach (Appointment item in appointments) { lstData.Add(new ExchangeData { UniqueId = item.Id.UniqueId, StartDate = item.Start.ToString("dd-MM-yyyy HH:mm"), Subject = item.Subject, Organizer = item.Organizer.Address, Categories = item.Categories.ToString(), IsSelected = (item.Subject.StartsWith("Canceled:", StringComparison.OrdinalIgnoreCase) || item.Subject.StartsWith("Abgesagt:", StringComparison.OrdinalIgnoreCase)) }); } //group by with Subject, start date var duplicates = from p in lstData.Where(p => !p.IsSelected) group p by new { p.Subject, p.StartDate } into q where q.Count() > 1 select new ExchangeData() { Subject = q.Key.Subject, StartDate = q.Key.StartDate }; var exchangeDatas = duplicates as ExchangeData[] ?? duplicates.ToArray(); if (exchangeDatas?.Length > 0) { foreach (var item in lstData.Where(p => !p.IsSelected)) { if (exchangeDatas.Any(p => string.Equals(p.Subject, item.Subject) && string.Equals(p.StartDate, item.StartDate))) { item.IsSelected = true; } } } } } } catch (Exception e) { WriteLog(e.Message); } return(lstData); }
//private string GatherChanges( ItemChange oItemChange) //{ private string GatherChanges(List <Item> oItemList) { StringBuilder oSB = new StringBuilder(); //List<Item> itemList = new List<Item>(); //itemList.Add(oItemChange.Item); PropertySet oPropertySet = new PropertySet(BasePropertySet.FirstClassProperties); ServiceResponseCollection <ServiceResponse> oServiceResponse = null; try { oSB.AppendLine(""); oSB.AppendFormat("[Calling LoadPropertiesForItems]-------------------------\r\n"); CurrentService.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. oServiceResponse = CurrentService.LoadPropertiesForItems(oItemList, oPropertySet); } catch (ServiceObjectPropertyException oServiceObjectPropertyException) { //MessageBox.Show(oXmlSchemaInferenceException.ToString(), "XmlSchemaInferenceException"); oSB.AppendLine(""); oSB.Append("[ServiceObjectPropertyException - Exception of type 'ServiceObjectPropertyException' was thrown]!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n"); oSB.AppendFormat("Exception: {0}", oServiceObjectPropertyException.ToString()); } catch (NullReferenceException oNullReferenceException) { //MessageBox.Show(oXmlSchemaInferenceException.ToString(), "XmlSchemaInferenceException"); oSB.AppendLine(""); oSB.Append("[NullReferenceException - Exception of type 'NullReferenceException' was thrown]!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n"); oSB.AppendFormat("Exception: {0}", oNullReferenceException.ToString()); } catch (NoNullAllowedException oNoNullAllowedException) { //MessageBox.Show(oXmlSchemaInferenceException.ToString(), "XmlSchemaInferenceException"); oSB.AppendLine(""); oSB.Append("[NoNullAllowedException - Exception of type 'NoNullAllowedException' was thrown]!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n"); oSB.AppendFormat("Exception: {0}", oNoNullAllowedException.ToString()); } catch (System.Xml.Schema.XmlSchemaInferenceException oXmlSchemaInferenceException) { //MessageBox.Show(oXmlSchemaInferenceException.ToString(), "XmlSchemaInferenceException"); oSB.AppendLine(""); oSB.Append("[LoadPropertiesForItems - Exception of type 'XmlSchemaInferenceException' was thrown]!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n"); oSB.AppendFormat("Exception: {0}", oXmlSchemaInferenceException.ToString()); } catch (System.Xml.Schema.XmlSchemaValidationException oXmlSchemaValidationException) { //MessageBox.Show(oXmlSchemaValidationException.ToString(), "XmlSchemaValidationException"); oSB.AppendLine(""); oSB.Append("[LoadPropertiesForItems - Exception of type 'XmlSchemaValidationException' was thrown]!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n"); oSB.AppendFormat("Exception: {0}", oXmlSchemaValidationException.ToString()); } catch (System.Xml.Schema.XmlSchemaException oXmlSchemaException) { //MessageBox.Show(oXmlSchemaException.ToString(), "XmlSchemaException"); oSB.AppendLine(""); oSB.Append("[LoadPropertiesForItems - Exception of type 'XmlSchemaException' was thrown]!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n"); oSB.AppendFormat("Exception: {0}", oXmlSchemaException.ToString()); } catch (XmlException oXmlException) { //MessageBox.Show(oXmlException.ToString(), "XmlException"); oSB.AppendLine(""); oSB.Append("[LoadPropertiesForItems - Exception of type 'XmlException' was thrown]!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n"); oSB.AppendFormat("Exception: {0}", oXmlException.ToString()); } catch (InvalidEnumArgumentException oInvalidEnumArgumentException) { //MessageBox.Show(oXmlException.ToString(), "XmlException"); oSB.AppendLine(""); oSB.Append("[LoadPropertiesForItems - Exception of type 'InvalidEnumArgumentException' was thrown]!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n"); oSB.AppendFormat("Exception: {0}", oInvalidEnumArgumentException.ToString()); } catch (ArgumentNullException oArgumentNullException) { //MessageBox.Show(oXmlException.ToString(), "XmlException"); oSB.AppendLine(""); oSB.Append("[LoadPropertiesForItems - Exception of type 'ArgumentNullException' was thrown]!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n"); oSB.AppendFormat("Exception: {0}", oArgumentNullException.ToString()); } catch (ArgumentOutOfRangeException oArgumentOutOfRangeException) { //MessageBox.Show(oXmlException.ToString(), "XmlException"); oSB.AppendLine(""); oSB.Append("[LoadPropertiesForItems - Exception of type 'ArgumentOutOfRangeException' was thrown]!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n"); oSB.AppendFormat("Exception: {0}", oArgumentOutOfRangeException.ToString()); } catch (ArgumentException oArgumentException) { //MessageBox.Show(oXmlException.ToString(), "XmlException"); oSB.AppendLine(""); oSB.Append("[LoadPropertiesForItems - Exception of type 'ArgumentException' was thrown]!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n"); oSB.AppendFormat("Exception: {0}", oArgumentException.ToString()); } catch (Exception ex) { //MessageBox.Show(ex.ToString(), "Exception"); oSB.AppendLine(""); oSB.Append("[LoadPropertiesForItems - Exception of type 'Exception' was thrown]!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n"); oSB.AppendFormat("Exception: {0}", ex.ToString()); } oSB.AppendLine(""); oSB.AppendFormat("[ServiceResponse]-------------------------------------------------------------\r\n"); if (oServiceResponse == null) { oSB.AppendLine("Service response was null."); } else { foreach (ServiceResponse o in oServiceResponse) { oSB.AppendFormat("ErrorCode: {0}\r\n", o.ErrorCode.ToString()); oSB.AppendLine(""); oSB.AppendFormat("ErrorMessage: {0}\r\n", o.ErrorMessage); oSB.AppendLine(""); if (o.ErrorDetails != null) { if (o.ErrorDetails.Count != 0) { oSB.AppendFormat("ErrorDetails: \r\n"); foreach (KeyValuePair <string, string> oProp in o.ErrorDetails) { oSB.AppendFormat(" Key: {0}\r\n", oProp.Key); oSB.AppendFormat(" Value: {0}\r\n", oProp.Value); oSB.AppendLine(""); } } } if (o.ErrorProperties != null) { if (o.ErrorProperties.Count != 0) { oSB.AppendFormat("ErrorProperties: \r\n"); foreach (PropertyDefinitionBase oProps in o.ErrorProperties) { //oSB.AppendFormat(" ErrorProperties: {0}\r\n"); oSB.AppendFormat(" ToString(): {0}\r\n", oProps.ToString()); oSB.AppendFormat(" Type: {0}\r\n", oProps.Type); oSB.AppendFormat(" Version: {0}\r\n", oProps.Version); //System.Collections.ObjectModel.Collection<PropertyDefinitionBase> } } } oSB.AppendLine(""); oSB.AppendFormat("Result: {0}\r\n", o.Result.ToString()); oSB.AppendLine(""); } } int iItemTotal = oItemList.Count; int iItemCount = 0; foreach (Item oItem in oItemList) { iItemCount += 1; //lblStatus.Text = string.Format("Gathering properties for {0} of {1}.", iItemCount, iItemTotal); try { oSB.AppendLine(""); oSB.AppendFormat("[Item loaded by LoadPropertiesForItems]======================================\r\n"); oSB.AppendFormat("UniqueId: {0}\r\n", oItem.Id.UniqueId); AddItemProps(oItem, ref oSB); } catch (System.Xml.Schema.XmlSchemaInferenceException oXmlSchemaInferenceException) { //MessageBox.Show(oXmlSchemaInferenceException.ToString(), "XmlSchemaInferenceException"); oSB.AppendLine(""); oSB.Append("[Exception of type 'XmlSchemaInferenceException' was thrown]!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n"); oSB.AppendFormat("Exception: {0}", oXmlSchemaInferenceException.ToString()); } catch (System.Xml.Schema.XmlSchemaValidationException oXmlSchemaValidationException) { //MessageBox.Show(oXmlSchemaValidationException.ToString(), "XmlSchemaValidationException"); oSB.AppendLine(""); oSB.Append("[Exception of type 'XmlSchemaValidationException' was thrown]!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n"); oSB.AppendFormat("Exception: {0}", oXmlSchemaValidationException.ToString()); } catch (System.Xml.Schema.XmlSchemaException oXmlSchemaException) { //MessageBox.Show(oXmlSchemaException.ToString(), "XmlSchemaException"); oSB.AppendLine(""); oSB.Append("[Exception of type 'XmlSchemaException' was thrown]!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n"); oSB.AppendFormat("Exception: {0}", oXmlSchemaException.ToString()); } catch (XmlException oXmlException) { //MessageBox.Show(oXmlException.ToString(), "XmlException"); oSB.AppendLine(""); oSB.Append("[Exception of type 'XmlException' was thrown]!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n"); oSB.AppendFormat("Exception: {0}", oXmlException.ToString()); } catch (Exception ex) { //MessageBox.Show(ex.ToString(), "Exception"); oSB.AppendLine(""); oSB.Append("[Exception of type 'Exception' was thrown]!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n"); oSB.AppendFormat("Exception: {0}", ex.ToString()); } oSB.AppendLine(""); oSB.Append(""); } string sRet = oSB.ToString(); return(sRet); }
/// <summary> /// Moves two items between folders in a batched call to EWS. /// </summary> /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param> private static void MoveManyItems(ExchangeService service) { // Create two items to be moved. You can move any item type in your Exchange mailbox. // You will need to save these items to your Exchange mailbox before they can be moved. EmailMessage email1 = new EmailMessage(service); email1.Subject = "Draft email one"; email1.Body = new MessageBody(BodyType.Text, "Draft body of the mail."); EmailMessage email2 = new EmailMessage(service); email2.Subject = "Draft email two"; email1.Body = new MessageBody(BodyType.Text, "Draft body of the mail."); Collection <EmailMessage> messages = new Collection <EmailMessage>(); messages.Add(email1); messages.Add(email2); try { // This results in a CreateItem operation call to EWS. The items are created on the server. // The response contains the item identifiers of the newly created items. The items on the client // now have item identifiers, which you need in order to move the item. ServiceResponseCollection <ServiceResponse> responses = service.CreateItems(messages, WellKnownFolderName.Drafts, MessageDisposition.SaveOnly, null); if (responses.OverallResult == ServiceResult.Success) { Console.WriteLine("Successfully created items to be copied."); } else { throw new Exception("The batch creation of the email message draft items was not successful."); } } catch (ServiceResponseException ex) { Console.WriteLine("Error: {0}", ex.Message); } // Get the item identifiers of the items to be moved in a batch operation. Collection <ItemId> itemIds = new Collection <ItemId>(); foreach (EmailMessage email in messages) { itemIds.Add(email.Id); } try { // You can move items in a batch request. This will result in MoveItem operation call to EWS. // Unlike the EmailMessage.Move method, the batch request takes a collection of item identifiers, // which identify the items that will be moved. This sample moves the items to the DeletedItems folder. ServiceResponseCollection <MoveCopyItemResponse> responses = service.MoveItems(itemIds, WellKnownFolderName.DeletedItems); if (responses.OverallResult == ServiceResult.Success) { Console.WriteLine("Successfully moved the items."); } else { throw new Exception("The batch move of the email message items was not successful."); } } catch (ServiceResponseException ex) { Console.WriteLine("Error: {0}", ex.Message); } }
// LoadItem // This will load an item by ID. // Test code to load a folder object with many properties - modify as needed for your code. bool LoadItem(ExchangeService oService, ItemId oItemId, out Item oItem) { bool bRet = true; ExtendedPropertyDefinition Prop_IsHidden = new ExtendedPropertyDefinition(0x10f4, MapiPropertyType.Boolean); // PR_ARCHIVE_TAG 0x3018 ExtendedPropertyDefinition Prop_PidTagPolicyTag = new ExtendedPropertyDefinition(0x66B1, MapiPropertyType.Long); // PR_POLICY_TAG 0x3019 Data type: PtypBinary, 0x0102 ExtendedPropertyDefinition Prop_PR_POLICY_TAG = new ExtendedPropertyDefinition(0x3019, MapiPropertyType.Binary); // PR_RETENTION_FLAGS 0x301D (12317) PtypInteger32 ExtendedPropertyDefinition Prop_Retention_Flags = new ExtendedPropertyDefinition(0x301D, MapiPropertyType.Integer); // PR_RETENTION_PERIOD 0x301A (12314) PtypInteger32, 0x0003 ExtendedPropertyDefinition Prop_Retention_Period = new ExtendedPropertyDefinition(0x301A, MapiPropertyType.Integer); Item oReturnItem = null; oItem = null; List <ItemId> oItems = new List <ItemId>(); oItems.Add(oItemId); PropertySet oPropertySet = new PropertySet( BasePropertySet.IdOnly, EmailMessageSchema.ItemClass, EmailMessageSchema.Subject); // Add more properties? oPropertySet.Add(Prop_IsHidden); oPropertySet.Add(EmailMessageSchema.DateTimeCreated); oPropertySet.Add(EmailMessageSchema.DateTimeReceived); oPropertySet.Add(EmailMessageSchema.DateTimeSent); //oPropertySet.Add(EmailMessageSchema.RetentionDate); oPropertySet.Add(EmailMessageSchema.ToRecipients); oPropertySet.Add(EmailMessageSchema.MimeContent); //oPropertySet.Add(EmailMessageSchema.StoreEntryId); oPropertySet.Add(EmailMessageSchema.Size); oPropertySet.Add(Prop_Retention_Period); oPropertySet.Add(Prop_PR_POLICY_TAG); oPropertySet.Add(Prop_Retention_Flags); int iVal = 0; long lVal = 0; object oVal = null; bool boolVal = false; ServiceResponseCollection <GetItemResponse> oGetItemResponses = oService.BindToItems(oItems, oPropertySet); StringBuilder oSB = new StringBuilder(); foreach (GetItemResponse oGetItemResponse in oGetItemResponses) { switch (oGetItemResponse.Result) { case ServiceResult.Success: oReturnItem = oGetItemResponse.Item; oSB.AppendFormat("Subject: {0}\r\n", oReturnItem.Subject); oSB.AppendFormat("Class: {0}\r\n", oReturnItem.ItemClass); oSB.AppendFormat("DateTimeCreated: {0}\r\n", oReturnItem.DateTimeCreated.ToString()); oSB.AppendFormat("Size: {0}\r\n", oReturnItem.Size.ToString()); if (oReturnItem.TryGetProperty(Prop_IsHidden, out boolVal)) { oSB.AppendFormat("PR_IS_HIDDEN: {0}\r\n", boolVal); } else { oSB.AppendLine("PR_IS_HIDDEN: Not found."); } if (oReturnItem.TryGetProperty(Prop_PR_POLICY_TAG, out oVal)) { oSB.AppendFormat("PR_POLICY_TAG: {0}\r\n", oVal); } //else // oSB.AppendLine("PR_RETENTION_TAG: Not found."); if (oReturnItem.TryGetProperty(Prop_Retention_Flags, out iVal)) { oSB.AppendFormat("PR_RETENTION_FLAGS: {0}\r\n", iVal); } //else // oSB.AppendLine("PR_RETENTION_FLAGS: Not found."); if (oReturnItem.TryGetProperty(Prop_Retention_Period, out iVal)) { oSB.AppendFormat("PR_RETENTION_PERIOD: {0}\r\n", iVal); } //else // oSB.AppendLine("PR_RETENTION_PERIOD: Not found."); //// The following is for geting the MIME string //if (oGetItemResponse.Item.MimeContent == null) //{ // // Do something //} //UTF8Encoding oUTF8Encoding = new UTF8Encoding(); //string sMIME = oUTF8Encoding.GetString(oGetItemResponse.Item.MimeContent.Content); MessageBox.Show(oSB.ToString(), "ServiceResult.Success"); break; case ServiceResult.Error: string sError = "ErrorCode: " + oGetItemResponse.ErrorCode.ToString() + "\r\n" + "\r\nErrorMessage: " + oGetItemResponse.ErrorMessage + "\r\n"; MessageBox.Show(sError, "ServiceResult.Error"); break; case ServiceResult.Warning: string sWarning = "ErrorCode: " + oGetItemResponse.ErrorCode.ToString() + "\r\n" + "\r\nErrorMessage: " + oGetItemResponse.ErrorMessage + "\r\n"; MessageBox.Show(sWarning, "ServiceResult.Warning"); break; //default: // // Should never get here. // string sSomeError = // "ErrorCode: " + oGetItemResponse.ErrorCode.ToString() + "\r\n" + // "\r\nErrorMessage: " + oGetItemResponse.ErrorMessage + "\r\n"; // MessageBox.Show(sSomeError, "Some sort of error"); // break; } } oItem = oReturnItem; return(bRet); }
private MailItem[] getMailItem(ServiceResponseCollection<GetItemResponse> items, ExchangeService service) { return items.Select(item => { return new MailItem() { message = EmailMessage.Bind(service, item.Item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments)), From = ((Microsoft.Exchange.WebServices.Data.EmailAddress)item.Item[EmailMessageSchema.From]).Address, Recipients = ((Microsoft.Exchange.WebServices.Data.EmailAddressCollection)item.Item[EmailMessageSchema.ToRecipients]).Select(recipient => recipient.Address).ToArray(), Subject = item.Item.Subject, Body = item.Item.Body.ToString(), attachment = item.Item.Attachments.ToList(), }; }).ToArray(); }
//private string DeNullString(string s) //{ // if (s == null) // return ""; // else // return s; //} // LoadItem // This will load an item by ID. // Test code to load a folder object with many properties - modify as needed for your code. bool LoadItem(ExchangeService oService, ItemId oItemId, out Item oItem) { bool bRet = true; ExtendedPropertyDefinition Prop_IsHidden = new ExtendedPropertyDefinition(0x10f4, MapiPropertyType.Boolean); Item oReturnItem = null; oItem = null; List <ItemId> oItems = new List <ItemId>(); oItems.Add(oItemId); PropertySet oPropertySet = new PropertySet( BasePropertySet.IdOnly, EmailMessageSchema.ItemClass, EmailMessageSchema.Subject); // Add more properties? oPropertySet.Add(Prop_IsHidden); oPropertySet.Add(EmailMessageSchema.DateTimeCreated); oPropertySet.Add(EmailMessageSchema.DateTimeReceived); oPropertySet.Add(EmailMessageSchema.DateTimeSent); //oPropertySet.Add(EmailMessageSchema.RetentionDate); oPropertySet.Add(EmailMessageSchema.ToRecipients); oPropertySet.Add(EmailMessageSchema.MimeContent); oPropertySet.Add(EmailMessageSchema.StoreEntryId); oPropertySet.Add(EmailMessageSchema.Size); oService.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. ServiceResponseCollection <GetItemResponse> oGetItemResponses = oService.BindToItems(oItems, oPropertySet); foreach (GetItemResponse oGetItemResponse in oGetItemResponses) { switch (oGetItemResponse.Result) { case ServiceResult.Success: oReturnItem = oGetItemResponse.Item; // EmailMessage oEmailMessage = (EmailMessage)oReturnItem; // recasting example MessageBox.Show("ServiceResult.Success"); //// The following is for geting the MIME string //if (oGetItemResponse.Item.MimeContent == null) //{ // // Do something //} //UTF8Encoding oUTF8Encoding = new UTF8Encoding(); //string sMIME = oUTF8Encoding.GetString(oGetItemResponse.Item.MimeContent.Content); break; case ServiceResult.Error: string sError = "ErrorCode: " + oGetItemResponse.ErrorCode.ToString() + "\r\n" + "\r\nErrorMessage: " + oGetItemResponse.ErrorMessage + "\r\n"; MessageBox.Show(sError, "ServiceResult.Error"); break; case ServiceResult.Warning: string sWarning = "ErrorCode: " + oGetItemResponse.ErrorCode.ToString() + "\r\n" + "\r\nErrorMessage: " + oGetItemResponse.ErrorMessage + "\r\n"; MessageBox.Show(sWarning, "ServiceResult.Warning"); break; //default: // // Should never get here. // string sSomeError = // "ErrorCode: " + oGetItemResponse.ErrorCode.ToString() + "\r\n" + // "\r\nErrorMessage: " + oGetItemResponse.ErrorMessage + "\r\n"; // MessageBox.Show(sSomeError, "Some sort of error"); // break; } } oItem = oReturnItem; return(bRet); }
public ServiceResponse EndEwsCall(IAsyncResult asyncResult) { ServiceResponseCollection <SearchMailboxesResponse> serviceResponseCollection = this.service.EndSearchMailboxes(asyncResult); return(serviceResponseCollection[0]); }
} // End Sub MoveMessage /// <summary> /// Creates and tries to send three email messages with one call to EWS. The third email message intentionally fails /// to demonstrate how EWS returns errors for batch requests. /// </summary> /// <param name="service">A valid ExchangeService object with credentials and the EWS URL.</param> static void SendBatchEmails(ExchangeService service) { // Create three separate email messages. EmailMessage message1 = new EmailMessage(service); message1.ToRecipients.Add("*****@*****.**"); message1.ToRecipients.Add("*****@*****.**"); message1.Subject = "Status Update"; message1.Body = "Project complete!"; EmailMessage message2 = new EmailMessage(service); message2.ToRecipients.Add("*****@*****.**"); message2.Subject = "High priority work items"; message2.Importance = Importance.High; message2.Body = "Finish estimate by EOD!"; EmailMessage message3 = new EmailMessage(service); message3.BccRecipients.Add("*****@*****.**"); message3.BccRecipients.Add("user2contoso.com"); // Invalid email address format. message3.Subject = "Surprise party!"; message3.Body = "Don't tell anyone. It will be at 6:00 at Aisha's house. Shhh!"; message3.Categories.Add("Personal Party"); System.Collections.ObjectModel.Collection <EmailMessage> msgs = new System.Collections.ObjectModel.Collection <EmailMessage>() { message1, message2, message3 }; try { // Send the batch of email messages. This results in a call to EWS. The response contains the results of the batched request to send email messages. ServiceResponseCollection <ServiceResponse> response = service.CreateItems(msgs, WellKnownFolderName.Drafts, MessageDisposition.SendOnly, null); // Check the response to determine whether the email messages were successfully submitted. if (response.OverallResult == ServiceResult.Success) { System.Console.WriteLine("All email messages were successfully submitted"); return; } int counter = 1; /* If the response was not an overall success, access the errors. * Results are returned in the order that the action was submitted. For example, the attempt for message1 * will be represented by the first result since it was the first one added to the collection. * Errors are not returned if an NDR is returned. */ foreach (ServiceResponse resp in response) { System.Console.WriteLine("Result (message {0}): {1}", counter, resp.Result); System.Console.WriteLine("Error Code: {0}", resp.ErrorCode); System.Console.WriteLine("Error Message: {0}\r\n", resp.ErrorMessage); counter++; } } catch (System.Exception e) { System.Console.WriteLine(e.Message); } }
// LoadFolder // This will load an Folder by ID. // Test code to load a folder object with many properties - modify as needed for your code. private bool LoadFolder(ExchangeService oService, FolderId oFolderId, out Folder oFolder) { // https://blogs.msdn.microsoft.com/akashb/2013/06/13/generating-a-report-which-folders-have-a-personal-tag-applied-to-it-using-ews-managed-api-from-powershell-exchange-2010/ bool bRet = true; Folder oReturnFolder = null; oFolder = null; List <FolderId> oFolders = new List <FolderId>(); oFolders.Add(oFolderId); ExtendedPropertyDefinition Prop_IsHidden = new ExtendedPropertyDefinition(0x10f4, MapiPropertyType.Boolean); // Folder Path ExtendedPropertyDefinition Prop_PR_FOLDER_PATH = new ExtendedPropertyDefinition(26293, MapiPropertyType.String); // PR_POLICY_TAG 0x3019 Data type: PtypBinary, 0x0102 ExtendedPropertyDefinition Prop_PR_POLICY_TAG = new ExtendedPropertyDefinition(0x3019, MapiPropertyType.Binary); // PR_RETENTION_TAG 0x3019 (12313) //ExtendedPropertyDefinition Prop_Retention_Tag = new ExtendedPropertyDefinition(0x3019, MapiPropertyType.Integer); // PR_RETENTION_FLAGS 0x301D (12317) PtypInteger32 ExtendedPropertyDefinition Prop_Retention_Flags = new ExtendedPropertyDefinition(0x301D, MapiPropertyType.Integer); // PR_RETENTION_PERIOD 0x301A (12314) PtypInteger32, 0x0003 ExtendedPropertyDefinition Prop_Retention_Period = new ExtendedPropertyDefinition(0x301A, MapiPropertyType.Integer); // http://gsexdev.blogspot.com/2011/04/using-ews-to-calculate-age-of-items-and.html#!/2011/04/using-ews-to-calculate-age-of-items-and.html // PR_FOLDER_TYPE 0x3601 (13825) ExtendedPropertyDefinition Prop_PR_FOLDER_TYPE = new ExtendedPropertyDefinition(0x3601, MapiPropertyType.Integer); // PR_MESSAGE_SIZE_EXTENDED 0x0E08 (3592) PT_I8 https://msdn.microsoft.com/en-us/library/office/cc839933.aspx ExtendedPropertyDefinition Prop_PR_MESSAGE_SIZE_EXTENDED = new ExtendedPropertyDefinition(0x0E08, MapiPropertyType.Long); // PR_DELETED_MESSAGE_SIZE_EXTENDED 0x669B (26267) PtypInteger64, 0x0014 ExtendedPropertyDefinition Prop_PR_DELETED_MESSAGE_SIZE_EXTENDED = new ExtendedPropertyDefinition(0x669B, MapiPropertyType.Long); // PR_ATTACH_ON_NORMAL_MSG_COUNT 0x66B1 ExtendedPropertyDefinition Prop_PR_ATTACH_ON_NORMAL_MSG_COUNT = new ExtendedPropertyDefinition(0x66B1, MapiPropertyType.Long); // PR_ARCHIVE_TAG 0x3018 ExtendedPropertyDefinition Prop_PidTagPolicyTag = new ExtendedPropertyDefinition(0x66B1, MapiPropertyType.Long); // private static ExtendedPropertyDefinition Prop_PidTagArchiveTag = new ExtendedPropertyDefinition(0x3018, MapiPropertyType.Binary); // Guid of Archive tag - PR_ARCHIVE_TAG - PidTagArchiveTag // private static ExtendedPropertyDefinition Prop_PidTagPolicyTag = new ExtendedPropertyDefinition(0x3019, MapiPropertyType.Integer); // Item - PidTagPolicyTag - PR_POLICY_TAG // private static ExtendedPropertyDefinition Prop_PidTagRetentionPeriod = new ExtendedPropertyDefinition(0x301A, MapiPropertyType.Integer); // Message - PidTagRetentionPeriod - PR_RETENTION_PERIOD PropertySet oPropertySet = new PropertySet( BasePropertySet.IdOnly, FolderSchema.FolderClass, FolderSchema.DisplayName, Prop_IsHidden); // Add more properties? oPropertySet.Add(FolderSchema.TotalCount); oPropertySet.Add(FolderSchema.UnreadCount); //oPropertySet.Add(FolderSchema.WellKnownFolderName); oPropertySet.Add(FolderSchema.ChildFolderCount); // oPropertySet.Add(Prop_FolderPath); //oPropertySet.Add(Prop_Retention_Tag); oPropertySet.Add(Prop_Retention_Period); oPropertySet.Add(Prop_PR_POLICY_TAG); oPropertySet.Add(Prop_Retention_Flags); oPropertySet.Add(Prop_PR_FOLDER_TYPE); oPropertySet.Add(Prop_PR_FOLDER_PATH); oPropertySet.Add(Prop_PR_MESSAGE_SIZE_EXTENDED); oPropertySet.Add(Prop_PR_DELETED_MESSAGE_SIZE_EXTENDED); oPropertySet.Add(Prop_PR_ATTACH_ON_NORMAL_MSG_COUNT); // https://blogs.msdn.microsoft.com/akashb/2011/08/10/stamping-retention-policy-tag-using-ews-managed-api-1-1-from-powershellexchange-2010/ StringBuilder oSB = new StringBuilder(); int iVal = 0; long lVal = 0; string sVal = string.Empty; object oVal = null; ServiceResponseCollection <GetFolderResponse> oGetFolderResponses = oService.BindToFolders(oFolders, oPropertySet); foreach (GetFolderResponse oGetItemResponse in oGetFolderResponses) { switch (oGetItemResponse.Result) { case ServiceResult.Success: oReturnFolder = oGetItemResponse.Folder; oSB.AppendFormat("DisplayName: {0}\r\n", oReturnFolder.DisplayName); oSB.AppendFormat("FolderClass: {0}\r\n", oReturnFolder.FolderClass); if (oReturnFolder.TryGetProperty(Prop_PR_FOLDER_TYPE, out iVal)) { oSB.AppendFormat("PR_FOLDER_TYPE: {0}\r\n", iVal); } else { oSB.AppendLine("PR_FOLDER_TYPE: Not found."); } string sPath = string.Empty; if (EwsFolderHelper.GetFolderPath(oReturnFolder, ref sPath)) { oSB.AppendFormat("Prop_PR_FOLDER_PATH: {0}\r\n", sPath); } else { oSB.AppendLine("Prop_PR_FOLDER_PATH: Not found."); } if (oReturnFolder.TryGetProperty(Prop_PR_MESSAGE_SIZE_EXTENDED, out lVal)) { oSB.AppendFormat("PR_MESSAGE_SIZE_EXTENDED: {0}\r\n", lVal); } else { oSB.AppendLine("PR_MESSAGE_SIZE_EXTENDED: Not found."); } if (oReturnFolder.TryGetProperty(Prop_PR_DELETED_MESSAGE_SIZE_EXTENDED, out lVal)) { oSB.AppendFormat("PR_DELETED_MESSAGE_SIZE_EXTENDED: {0}\r\n", lVal); } //else // oSB.AppendLine("PR_DELETED_MESSAGE_SIZE_EXTENDED: Not found."); if (oReturnFolder.TryGetProperty(Prop_PR_ATTACH_ON_NORMAL_MSG_COUNT, out lVal)) { oSB.AppendFormat("PR_ATTACH_ON_NORMAL_MSG_COUNT: {0}\r\n", lVal); } else { oSB.AppendLine("PR_ATTACH_ON_NORMAL_MSG_COUNT: Not found."); } MessageBox.Show(oSB.ToString(), "ServiceResult.Success"); break; case ServiceResult.Error: string sError = "ErrorCode: " + oGetItemResponse.ErrorCode.ToString() + "\r\n" + "\r\nErrorMessage: " + oGetItemResponse.ErrorMessage + "\r\n"; if (oGetItemResponse.ErrorProperties.Count > 0) { sError += "\r\nErrorProperties: "; foreach (ExtendedPropertyDefinition x in oGetItemResponse.ErrorProperties) { if (x.Name != null) { sError += "\r\n Name: " + x.Name; } if (x.Tag != null) { //sError += "\r\n Tag: " + x.Tag; iVal = (int)x.Tag; if (iVal == 13825) { sError += string.Format("\r\n PR_FOLDER_TYPE Hex: {00:X} Int: {1} ", iVal, iVal); } if (iVal == 26293) { sError += string.Format("\r\n Prop_PR_FOLDER_PATH Hex: {00:X} Int: {1} ", iVal, iVal); } if (iVal == 3592) { sError += string.Format("\r\n PR_MESSAGE_SIZE_EXTENDED Hex: {00:X} Int: {1} ", iVal, iVal); } if (iVal == 26267) { sError += string.Format("\r\n PR_DELETED_MESSAGE_SIZE_EXTENDED Hex: {00:X} Int: {1} ", iVal, iVal); } } if (x.Type != null) { sError += "\r\n Type: " + x.Type; } // sHex = string.Format("{00:X}", iValue).PadLeft(2, '0'); } //for (int i= 0; i < oGetItemResponse.ErrorProperties.Count; i++) //{ //} } MessageBox.Show(sError, "ServiceResult.Error"); break; case ServiceResult.Warning: string sWarning = "ErrorCode: " + oGetItemResponse.ErrorCode.ToString() + "\r\n" + "\r\nErrorMessage: " + oGetItemResponse.ErrorMessage + "\r\n"; MessageBox.Show(sWarning, "ServiceResult.Warning"); break; //default: // // Should never get here. // string sSomeError = // "ErrorCode: " + oGetItemResponse.ErrorCode.ToString() + "\r\n" + // "\r\nErrorMessage: " + oGetItemResponse.ErrorMessage + "\r\n"; // MessageBox.Show(sSomeError, "Some sort of error"); // break; } } oFolder = oReturnFolder; return(bRet); }
/// <summary> /// Create meetings either one at a time or batch request the creation of meetings. Meetings /// are appointments that include attendees. /// </summary> /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param> private static void CreateMeeting(ExchangeService service) { bool demoBatchCreateMeeting = true; Appointment meeting1 = new Appointment(service); meeting1.Subject = "Status Meeting"; meeting1.Body = "The purpose of this meeting is to discuss status."; meeting1.Start = new DateTime(2013, 6, 1, 9, 0, 0); meeting1.End = meeting1.Start.AddHours(2); meeting1.Location = "Conf Room"; meeting1.RequiredAttendees.Add("*****@*****.**"); meeting1.RequiredAttendees.Add("*****@*****.**"); meeting1.OptionalAttendees.Add("*****@*****.**"); Appointment meeting2 = new Appointment(service); meeting2.Subject = "Lunch"; meeting2.Body = "The purpose of this meeting is to eat and be merry."; meeting2.Start = new DateTime(2013, 6, 1, 12, 0, 0); meeting2.End = meeting2.Start.AddHours(2); meeting2.Location = "Contoso cafe"; meeting2.RequiredAttendees.Add("*****@*****.**"); meeting2.RequiredAttendees.Add("*****@*****.**"); meeting2.OptionalAttendees.Add("*****@*****.**"); try { if (demoBatchCreateMeeting) // Show batch. { Collection <Appointment> meetings = new Collection <Appointment>(); meetings.Add(meeting1); meetings.Add(meeting2); // Create the batch of meetings. This results in a CreateItem operation call to EWS. ServiceResponseCollection <ServiceResponse> responses = service.CreateItems(meetings, WellKnownFolderName.Calendar, MessageDisposition.SendOnly, SendInvitationsMode.SendToAllAndSaveCopy); if (responses.OverallResult == ServiceResult.Success) { Console.WriteLine("You've successfully created a couple of meetings in a single call."); } else if (responses.OverallResult == ServiceResult.Warning) { Console.WriteLine("There are some issues with your batch request."); foreach (ServiceResponse response in responses) { if (response.Result == ServiceResult.Error) { Console.WriteLine("Error code: " + response.ErrorCode.ToString()); Console.WriteLine("Error message: " + response.ErrorMessage); } } } else // responses.OverallResult == ServiceResult.Error { Console.WriteLine("There are errors with your batch request."); foreach (ServiceResponse response in responses) { if (response.Result == ServiceResult.Error) { Console.WriteLine("Error code: " + response.ErrorCode.ToString()); Console.WriteLine("Error message: " + response.ErrorMessage); } } } } else // Show creation of a single meeting. { // Create a single meeting. This results in a CreateItem operation call to EWS. meeting1.Save(SendInvitationsMode.SendToAllAndSaveCopy); Console.WriteLine("You've successfully created a single meeting."); } } catch (Exception ex) { Console.WriteLine("Exception info: " + ex.Message); } }