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 bool DeleteBatch(IEnumerable <string> emailIds) { List <ItemId> itemIds = new List <ItemId>(); foreach (string emailId in emailIds) { itemIds.Add(new ItemId(emailId)); } try { if (_deleteToDeletedItems) { _exchangeService.DeleteItems(itemIds, DeleteMode.MoveToDeletedItems, SendCancellationsMode.SendToNone, AffectedTaskOccurrence.AllOccurrences); } else { _exchangeService.DeleteItems(itemIds, DeleteMode.HardDelete, SendCancellationsMode.SendToNone, AffectedTaskOccurrence.AllOccurrences); } return(true); } catch (Exception ex) { _logger.Error("An Error occured while deleting email batch", ex); return(false); } }
private void DeleteHeaders(IEnumerable <ItemId> itemIds) { if (itemIds.Any()) { _service.DeleteItems(itemIds, DeleteMode.HardDelete, null, null); } }
/// <summary> /// Delete the email /// </summary> public void Delete() { // Delete to the deleted items _exchangeService.DeleteItems( new[] { Email.Id }, DeleteMode.MoveToDeletedItems, SendCancellationsMode.SendToNone, AffectedTaskOccurrence.SpecifiedOccurrenceOnly); }
public static void ClearOutMailbox(string username, string password) { connectToExchangeService(username, password); List <Item> messages = RetrieveAllEmails(); while (messages.Count > 0) { _exchangeService.DeleteItems(messages.Select(x => x.Id).ToList(), DeleteMode.HardDelete, SendCancellationsMode.SendToNone, AffectedTaskOccurrence.AllOccurrences); messages = RetrieveAllEmails(); } System.Threading.Thread.Sleep(5000); }
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"); } }
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); } }
public void Start(object o) { string logpath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "stafferror.log"); if (File.Exists(logpath)) { File.Delete(logpath); } StreamWriter sr = new StreamWriter(logpath); try { ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); if (string.IsNullOrEmpty(Properties.Settings.Default.Domain)) { service.Credentials = new WebCredentials(Properties.Settings.Default.EXIMPUser, Properties.Settings.Default.EXIMPPassword); } else { service.Credentials = new WebCredentials(Properties.Settings.Default.EXIMPUser, Properties.Settings.Default.EXIMPPassword, Properties.Settings.Default.Domain); } if (string.IsNullOrEmpty(Properties.Settings.Default.ExchangeUri)) { service.AutodiscoverUrl(Properties.Settings.Default.EXIMPUser, RedirectionUrlValidationCallback); } else { service.Url = new Uri(Properties.Settings.Default.ExchangeUri + "/ews/exchange.asmx"); } Terms terms = new Terms(); staff = o as List <Staff>; if (Initialized != null) { Initialized(staff.Count); } List <Appointment> Appointments = new List <Appointment>(); XmlDocument doc = new XmlDocument(); doc.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "staffmapping.xml")); foreach (Staff s in staff) { try { if (doc.SelectSingleNode("/staffmappings/staff[@first=\"" + s.FirstName + "\" and @last=\"" + s.Surname + "\"]") != null) { this.Current = "Removing previous appointments for " + s.Title + " " + s.FirstName + " " + s.Surname; if (Updated != null) { Updated(); } service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, doc.SelectSingleNode("/staffmappings/staff[@first=\"" + s.FirstName + "\" and @last=\"" + s.Surname + "\"]").Attributes["email"].Value); SearchFilter.SearchFilterCollection searchFilter = new SearchFilter.SearchFilterCollection(); searchFilter.Add(new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, terms[0].StartDate)); searchFilter.Add(new SearchFilter.ContainsSubstring(AppointmentSchema.Subject, "Lesson:")); bool removecompleted = false; while (!removecompleted) { ItemView view = new ItemView(1000); view.PropertySet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.AppointmentType); FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Calendar, searchFilter, view); this.Current = "Found Existing" + findResults.TotalCount + " out of " + findResults.Items.Count + " for " + s.Title + " " + s.FirstName + " " + s.Surname; if (Updated != null) { Updated(); } var appsids = new List <ItemId>(); foreach (Item item in findResults.Items) { Appointment appt = item as Appointment; if (appt.AppointmentType == AppointmentType.RecurringMaster) { appsids.Add(appt.Id); } } this.Current = "Removing previous appointments for " + s.Title + " " + s.FirstName + " " + s.Surname + " " + appsids.Count; if (Updated != null) { Updated(); } try { if (appsids.Count > 0) { service.DeleteItems(appsids, DeleteMode.HardDelete, SendCancellationsMode.SendToNone, AffectedTaskOccurrence.AllOccurrences, true); } } catch { System.Threading.Thread.Sleep(1000); } var c = service.FindItems(WellKnownFolderName.Calendar, searchFilter, view).TotalCount; removecompleted = c == 0; if (!removecompleted) { removecompleted = c == 1; } if (!removecompleted) { this.Current = "Remove not completed, still " + c + " to remove for " + s.Title + " " + s.FirstName + " " + s.Surname; if (Updated != null) { Updated(); } System.Threading.Thread.Sleep(2000); } } this.Current = "Creating appointments for " + s.Title + " " + s.FirstName + " " + s.Surname; if (Updated != null) { Updated(); } var apps = new List <Appointment>(); foreach (Lesson l in s.Lessons) { foreach (Term t in terms) { try { if (t.HalfTerm.HasValue) { DateTime hts = t.HalfTerm.Value.StartDate; if (hts.DayOfWeek == DayOfWeek.Monday) { hts = hts.AddDays(-3); } DateTime hte = t.HalfTerm.Value.EndDate; if (hte.DayOfWeek == DayOfWeek.Friday) { hte = hte.AddDays(3); } if (apps.Count(f => f.Body.Text.Contains(GenBody(l, t.StartDate, hts))) == 0) { apps.Add(CreateApp(l, t.StartDate, hts, t.StartWeekNum == 2, service)); } if (hte < t.EndDate) { if (apps.Count(f => f.Body.Text.Contains(GenBody(l, hte, t.EndDate))) == 0) { apps.Add(CreateApp(l, hte, t.EndDate, t.WeekNum(hte) == 2, service)); } } } else if (apps.Count(f => f.Body.Text.Contains(GenBody(l, t.StartDate, t.EndDate))) == 0) { apps.Add(CreateApp(l, t.StartDate, t.EndDate, t.StartWeekNum == 2, service)); } } catch (Exception ex1) { sr.WriteLine(ex1.Message); sr.WriteLine(ex1.Source); sr.WriteLine(ex1); sr.WriteLine(s.ToString()); sr.Flush(); } } } this.Current = "Creating " + apps.Count + " appointments for " + s.Title + " " + s.FirstName + " " + s.Surname; if (Updated != null) { Updated(); } service.CreateItems(apps, null, MessageDisposition.SaveOnly, SendInvitationsMode.SendToNone); } } catch (Exception ex) { sr.WriteLine(ex.Message); sr.WriteLine(ex.Source); sr.WriteLine(ex); sr.WriteLine(s.ToString()); sr.Flush(); } this.Progress++; if (Updated != null) { Updated(); } } } catch (Exception e) { sr.WriteLine(e.Message); sr.WriteLine(e.Source); sr.WriteLine(e); } finally { sr.Close(); } if (Done != null) { Done(); } }
private void DownloadEmails() { _logger.AddLogEntry(_serviceName, "INPROGRESS", "Downloading emails", "DownloadEmails"); using (var _setting = new AppSettingService()) { var appSettings = _setting.Get(); ServicePointManager.ServerCertificateValidationCallback = (s, certificate, chain, sslPolicyErrors) => true; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); service.Credentials = new WebCredentials(appSettings.aps_rapids_email, appSettings.aps_rapids_password); service.Url = new Uri(appSettings.aps_rapids_service); service.PreAuthenticate = true; _logger.AddLogEntry(_serviceName, "INPROGRESS", "Reading O365 mailbox", "DownloadEmails"); ItemView view = new ItemView(int.MaxValue); FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, SetFilter(), view); _logger.AddLogEntry(_serviceName, "INFO", $"There are {findResults.Items?.Count} emails to process", "DownloadEmails"); // in case if deployed different location as background job string rapidsDirectoryUrl = System.Configuration.ConfigurationManager.AppSettings.Get("RapidsDirectoryUrl"); using (var _rapidsService = new RapidsService()) { foreach (Item item in findResults.Items) { _logger.AddLogEntry(_serviceName, "INPROGRESS", $"Processing email with Subject = {item.Subject}", "DownloadEmails"); var mailMessage = (EmailMessage)item; // format internalMessageId to be used as Id string messageID = mailMessage.InternetMessageId.Replace("<", "").Replace(">", ""); Model.rapids_mailbox newEmail = null; if (_rapidsService.FindByUID(messageID)) { service.DeleteItems(new List <ItemId> { new ItemId(mailMessage.Id.UniqueId) }, DeleteMode.MoveToDeletedItems, null, null); continue; } // load details item.Load(); try { newEmail = new Model.rapids_mailbox { rpd_attachments = item.Attachments.Count, rpd_body = item.Body, rpd_date = item.DateTimeReceived, rpd_created_by = "Import Service", rpd_created_date = DateTime.Now.ToEST(), rpd_from = string.Format("{0} <{1}>", mailMessage.From.Name, mailMessage.From.Address), rpd_subject = item.Subject, rpd_to = item.DisplayTo, rpd_uid = messageID, }; // save email into database _rapidsService.Create(newEmail); newEmail.rpd_body = newEmail.rpd_body.Replace("cid:", $"{rapidsDirectoryUrl}/RapidsAttachments/{newEmail.rpd_key}/"); #region ----- Save Attachments ----- // check if there are any attachments if (item.Attachments != null && item.Attachments.Count > 0) { _logger.AddLogEntry(_serviceName, "INPROGRESS", $"Processing attachments with Subject = {item.Subject}", "DownloadEmails"); string parentDirectory = System.Configuration.ConfigurationManager.AppSettings.Get("RapidsDirectory"); string attachmentDirectory = Path.Combine(parentDirectory, Convert.ToString(newEmail.rpd_key)); string attachmentDirectoryOthers = Path.Combine(attachmentDirectory, "Others"); // create directory if (!Directory.Exists(attachmentDirectory)) { Directory.CreateDirectory(attachmentDirectory); } if (!Directory.Exists(attachmentDirectoryOthers)) { Directory.CreateDirectory(attachmentDirectoryOthers); } // save attachments foreach (Attachment attach in item.Attachments) { if (attach.IsInline) { ((FileAttachment)attach).Load(Path.Combine(attachmentDirectory, attach.Name)); newEmail.rpd_body = newEmail.rpd_body.Replace(attach.ContentId, attach.Name); } else { ((FileAttachment)attach).Load(Path.Combine(attachmentDirectoryOthers, attach.Name)); string htmlForAttachment = "<div style=\"text-align: center; display: block; padding: 10px; \">"; string attachmentLink = $"{rapidsDirectoryUrl}/RapidsAttachments/{newEmail.rpd_key}/Others/{attach.Name}"; if (attach.Name.EndsWith(".txt") || attach.Name.EndsWith(".doc") || attach.Name.EndsWith(".docx")) { htmlForAttachment += $"<a href=\"{attachmentLink}\" target=\"_blank\">{attach.Name}</a>"; } else { htmlForAttachment += $"<img src=\"{attachmentLink}\" alt=\"{attach.Name}\" />"; } htmlForAttachment += "</div>"; if (string.IsNullOrEmpty(newEmail.rpd_attachment_html)) { newEmail.rpd_attachment_html = ""; } newEmail.rpd_attachment_html = newEmail.rpd_attachment_html + htmlForAttachment; if (!string.IsNullOrEmpty(attach.ContentId)) { newEmail.rpd_attachment_html = newEmail.rpd_attachment_html.Replace(attach.ContentId, attach.Name); } } } } #endregion // delete email once saved into database service.DeleteItems(new List <ItemId> { new ItemId(mailMessage.InternetMessageId) }, DeleteMode.MoveToDeletedItems, null, null); } catch (Exception ex) { if (newEmail != null) { newEmail.rpd_logs += ex.ToString(); } } finally { // save email attachments name changes, if any _rapidsService.Edit(newEmail); } } } } }
public static void BatchDeleteEmailItems(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.SoftDelete, 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) { System.Console.WriteLine("Email messages deleted successfully.\r\n"); } // If the method did not return success, print a message. else { System.Console.WriteLine("Not all email messages deleted successfully.\r\n"); } }
ExchangeResult ExecuteOperation(EmailOperation operation, string address, Dictionary <string, bool> processed = null) { // create processed addresses dictionary if it does not exist if (processed == null) { processed = new Dictionary <string, bool>(); } // dont reprocess this address if we have already processed it if (processed.ContainsKey(address)) { return(null); } // try to find a mailbox for the address on one of the tenants ExchangeService service = null; EmailAddress mailbox = null; foreach (WebCredentials cred in credentials) { service = new ExchangeService(); service.Credentials = cred; service.Url = new Uri(ConfigurationManager.AppSettings["url"]); try { NameResolutionCollection results = service.ResolveName("smtp:" + address); if (results.Count > 0) { mailbox = results[0].Mailbox; break; } } catch (Exception e) { return(new ExchangeResult(address, StatusCode.Error, "Failed to resolve name: " + e.Message)); } } // if we did not find a mailbox for the address on any of the tenants then report recipient not found if (mailbox == null) { return(new ExchangeResult(address, StatusCode.RecipientNotFound, "recipient not found")); } // add resolved address to processed list to prevent reprocessing processed.Add(mailbox.Address, true); // if this mailbox is a group/distribution list if (mailbox.MailboxType == MailboxType.PublicGroup) { // attempt to expand the group ExpandGroupResults group = null; try { group = service.ExpandGroup(mailbox.Address); } catch (Exception e) { // report failure to expand group if an exception occurs during expansion return(new ExchangeResult(mailbox.Address, StatusCode.Error, "Failed to expand group: " + e.Message)); } // for every member in the group ExchangeResult result = new ExchangeResult(); foreach (EmailAddress member in group.Members) { // recursively execute operation and log results result.Log(ExecuteOperation(operation, member.Address, processed)); } // return the results return(result); } // if this is just a regular mailbox else if (mailbox.MailboxType == MailboxType.Mailbox) { // set impersonation to the mailbox address service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, mailbox.Address); // attempt to get some info to see if impersonation worked try { DateTime?dt = service.GetPasswordExpirationDate(mailbox.Address); } catch (Exception e) { // if we were unable to impersonate the user then report error return(new ExchangeResult(mailbox.Address, StatusCode.Error, "impersonation failed: " + e.Message)); } // delete email if operation is delete if (operation == EmailOperation.Delete) { try { // find all instances of the email with message_id in the mailbox FolderView folderView = new FolderView(int.MaxValue); folderView.PropertySet = new PropertySet(BasePropertySet.IdOnly, FolderSchema.DisplayName); folderView.Traversal = FolderTraversal.Shallow; SearchFilter folderFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "AllItems"); FindFoldersResults folders = service.FindFolders(WellKnownFolderName.Root, folderFilter, folderView); SearchFilter filter = new SearchFilter.IsEqualTo(EmailMessageSchema.InternetMessageId, message_id); ItemView view = new ItemView(int.MaxValue); view.PropertySet = new PropertySet(BasePropertySet.IdOnly); view.Traversal = ItemTraversal.Shallow; List <ItemId> items = new List <ItemId>(); foreach (Item item in service.FindItems(folders.Folders[0].Id, filter, view)) { items.Add(item.Id); } // if no instances of the email were found in the mailbox then report message_id not found if (items.Count == 0) { return(new ExchangeResult(mailbox.Address, StatusCode.MessageNotFound, "message_id not found")); } // delete all found instances of the email with message_id from the mailbox foreach (ServiceResponse response in service.DeleteItems(items, DeleteMode.SoftDelete, null, null)) { // if we failed to delete an instance of the email then report an error if (response.Result != ServiceResult.Success) { string message = "failed to delete email: " + response.ErrorCode + " " + response.ErrorMessage; return(new ExchangeResult(mailbox.Address, StatusCode.Error, message)); } } } catch (Exception e) { //report any errors we encounter return(new ExchangeResult(mailbox.Address, StatusCode.Error, "failed to delete email: " + e.Message)); } } // recover email if operation is recover else if (operation == EmailOperation.Restore) { try { // find all instances of the email with message_id in the recoverable items folder SearchFilter filter = new SearchFilter.IsEqualTo(EmailMessageSchema.InternetMessageId, message_id); ItemView view = new ItemView(int.MaxValue); view.PropertySet = new PropertySet(BasePropertySet.IdOnly); view.Traversal = ItemTraversal.Shallow; List <ItemId> items = new List <ItemId>(); foreach (Item item in service.FindItems(WellKnownFolderName.RecoverableItemsDeletions, filter, view)) { items.Add(item.Id); } // if no instances of the email with message_id were found in the recoverable items folder of the mailbox if (items.Count == 0) { // report message_id not found return(new ExchangeResult(mailbox.Address, StatusCode.MessageNotFound, "message_id not found")); } // move every instance of the email with message_id in the recoverable items folder to the inbox foreach (ServiceResponse response in service.MoveItems(items, new FolderId(WellKnownFolderName.Inbox))) { // if we failed to move an instance of the email to the inbox then report an error if (response.Result != ServiceResult.Success) { string message = "failed to recover email: " + response.ErrorCode + " " + response.ErrorMessage; return(new ExchangeResult(mailbox.Address, StatusCode.Error, message)); } } } catch (Exception e) { // report any errors we encounter return(new ExchangeResult(mailbox.Address, StatusCode.Error, "failed to recover email: " + e.Message)); } } // report successful operation return(new ExchangeResult(mailbox.Address, StatusCode.Success, "success")); } // report that the mailbox type is not one of the supported types return(new ExchangeResult(mailbox.Address, StatusCode.Error, "Unsupported mailbox type: " + mailbox.MailboxType.ToString())); }
/// <summary> /// Deletes two items in a batched call to EWS. /// </summary> /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param> private static void DeleteManyItems(ExchangeService service) { // Create two items 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 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 delete the items. 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 item identifiers of the items to be deleted in a batch operation. Collection <ItemId> itemIds = new Collection <ItemId>(); foreach (EmailMessage email in messages) { itemIds.Add(email.Id); } try { // You can delete items in a batch request. This will result in a DeleteItem operation call to EWS. // Unlike the EmailMessage.Delete method, the batch request takes a collection of item identifiers // that identify the items that will be deleted. ServiceResponseCollection <ServiceResponse> responses = service.DeleteItems(itemIds, DeleteMode.HardDelete, null, null); if (responses.OverallResult == ServiceResult.Success) { Console.WriteLine("Successfully deleted the items."); } else { throw new Exception("The batch deletion of the email message items was not successful."); } } catch (ServiceResponseException ex) { Console.WriteLine("Error: {0}", ex.Message); } }
public void Process() { Progress = new SIMSExchange.Service.Progress() { Finished = false, Value = "" }; string logpath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Staff.log"); File.WriteAllText(logpath, ""); StreamWriter sr = new StreamWriter(File.Open(logpath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)); sr.AutoFlush = true; sr.WriteLine(Progress.Value = DateTime.Now.ToString() + " Wait 10s before start for SIMS to complete it's writing"); Thread.Sleep(new TimeSpan(0, 0, 10)); sr.WriteLine(Progress.Value = DateTime.Now.ToString() + " Starting Staff Processing"); try { XmlDocument doc = new XmlDocument(); doc.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "report.xml")); XmlNodeList nodes = doc.SelectNodes("/SuperStarReport/Record"); this.Progress.Total = 0; List <Staff> staff = new List <Staff>(); foreach (XmlNode node in nodes) { this.Progress.Total++; if (node.SelectSingleNode("Class") != null || (node.SelectSingleNode("ShortName") != null)) { Staff cs = null; foreach (Staff s in staff) { if (s.FirstName == (node.SelectSingleNode("Preferred_x0020_Forename") == null ? node.SelectSingleNode("ChosenName") : node.SelectSingleNode("Preferred_x0020_Forename")).InnerText && s.Surname == (node.SelectSingleNode("Legal_x0020_Surname") == null ? node.SelectSingleNode("LegalSurname") : node.SelectSingleNode("Legal_x0020_Surname")).InnerText) { cs = s; break; } } if (cs == null) { cs = new Staff(node); staff.Add(cs); } cs.Lessons.Add(new Lesson(node)); sr.WriteLine(this.Progress.Value = DateTime.Now.ToString() + " Found " + cs.Title + " " + cs.FirstName + " " + cs.Surname + " " + cs.Lessons.Last().Day + " " + cs.Lessons.Last().Start + " " + cs.Lessons.Last().Class); } } sr.WriteLine(this.Progress.Value = DateTime.Now.ToString() + " Found " + this.Progress.Total + " staff events"); ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); if (string.IsNullOrEmpty(Properties.Settings.Default.Domain)) { service.Credentials = new WebCredentials(Properties.Settings.Default.EXIMPUser, Properties.Settings.Default.EXIMPPassword); } else { service.Credentials = new WebCredentials(Properties.Settings.Default.EXIMPUser, Properties.Settings.Default.EXIMPPassword, Properties.Settings.Default.Domain); } if (string.IsNullOrEmpty(Properties.Settings.Default.ExchangeUri)) { service.AutodiscoverUrl(Properties.Settings.Default.EXIMPUser, RedirectionUrlValidationCallback); } else { service.Url = new Uri(Properties.Settings.Default.ExchangeUri + "/ews/exchange.asmx"); } Terms terms = new Terms(); List <Appointment> Appointments = new List <Appointment>(); this.Progress.Current = 0; sr.WriteLine(this.Progress.Value = DateTime.Now.ToString() + " Loading Staff Mappings"); XmlDocument doc2 = new XmlDocument(); doc2.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "staffmapping.xml")); foreach (Staff s in staff) { try { if (doc.SelectSingleNode("/staffmappings/staff[@first=\"" + s.FirstName + "\" and @last=\"" + s.Surname + "\"]") != null) { sr.WriteLine(this.Progress.Value = DateTime.Now.ToString() + " Removing previous appointments for " + s.Title + " " + s.FirstName + " " + s.Surname); service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, doc.SelectSingleNode("/staffmappings/staff[@first=\"" + s.FirstName + "\" and @last=\"" + s.Surname + "\"]").Attributes["email"].Value); SearchFilter.SearchFilterCollection searchFilter = new SearchFilter.SearchFilterCollection(); searchFilter.Add(new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, terms[0].StartDate)); searchFilter.Add(new SearchFilter.ContainsSubstring(AppointmentSchema.Subject, "Lesson:")); bool removecompleted = false; while (!removecompleted) { ItemView view = new ItemView(1000); view.PropertySet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.AppointmentType); FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Calendar, searchFilter, view); Console.WriteLine(findResults.TotalCount + " " + findResults.Items.Count); var appsids = new List <ItemId>(); foreach (Item item in findResults.Items) { Appointment appt = item as Appointment; if (appt.AppointmentType == AppointmentType.RecurringMaster) { appsids.Add(appt.Id); } } sr.WriteLine("Removing " + appsids.Count); if (appsids.Count > 0) { service.DeleteItems(appsids, DeleteMode.HardDelete, SendCancellationsMode.SendToNone, AffectedTaskOccurrence.AllOccurrences, true); } var c = service.FindItems(WellKnownFolderName.Calendar, searchFilter, view).TotalCount; removecompleted = c == 0; if (!removecompleted) { removecompleted = c == 1; } if (!removecompleted) { sr.WriteLine("Remove not completed, still " + c + " to remove"); System.Threading.Thread.Sleep(5000); } } sr.WriteLine(this.Progress.Value = DateTime.Now.ToString() + "Creating appointments for " + s.Title + " " + s.FirstName + " " + s.Surname); var apps = new List <Appointment>(); foreach (Lesson l in s.Lessons) { foreach (Term t in terms) { if (t.HalfTerm.HasValue) { DateTime hts = t.HalfTerm.Value.StartDate; if (hts.DayOfWeek == DayOfWeek.Monday) { hts = hts.AddDays(-3); } DateTime hte = t.HalfTerm.Value.EndDate; if (hte.DayOfWeek == DayOfWeek.Friday) { hte = hte.AddDays(3); } if (apps.Count(f => f.Body.Text.Contains(GenBody(l, t.StartDate, hts))) == 0) { apps.Add(CreateApp(l, t.StartDate, hts, t.StartWeekNum == 2, service)); } if (hte < t.EndDate) { if (apps.Count(f => f.Body.Text.Contains(GenBody(l, hte, t.EndDate))) == 0) { apps.Add(CreateApp(l, hte, t.EndDate, t.WeekNum(hte) == 2, service)); } } } else if (apps.Count(f => f.Body.Text.Contains(GenBody(l, t.StartDate, t.EndDate))) == 0) { apps.Add(CreateApp(l, t.StartDate, t.EndDate, t.StartWeekNum == 2, service)); } } } Console.WriteLine("Creating " + apps.Count + " appointments"); service.CreateItems(apps, null, MessageDisposition.SaveOnly, SendInvitationsMode.SendToNone); } } catch (Exception ex) { sr.WriteLine(DateTime.Now.ToString() + " Error " + ex.Message); sr.WriteLine(DateTime.Now.ToString() + " Error " + ex.Source); sr.WriteLine(DateTime.Now.ToString() + " Error " + ex); } this.Progress.Current++; } } catch (Exception e) { sr.WriteLine(DateTime.Now.ToString() + " Error " + e.Message); sr.WriteLine(DateTime.Now.ToString() + " Error " + e.Source); sr.WriteLine(DateTime.Now.ToString() + " Error " + e); } finally { sr.Close(); this.Progress.Finished = true; } }
/** * Function Undo Holiday Insertion */ static void UndoInsertion(ExchangeService service, List<string> mailboxes) { // Log file string datetimeString = DateTime.Now.ToString("MMddyyyy"); string logfile = "../../logs/" + datetimeString + "_undo_holiday_log.txt"; using (System.IO.StreamWriter log = new System.IO.StreamWriter(@logfile, true)) { // Mailboxes that need to be rerun that errored during this process List<string> rrmailboxes = new List<string>(); foreach (string mailbox in mailboxes) { // Find the holidays try { // Run search // Impersonate that User service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, mailbox); // Search String String category = "Holiday"; // Search Filter SearchFilter.IsEqualTo filter = new SearchFilter.IsEqualTo(AppointmentSchema.Categories, category); // Result Return Size, number of items ItemView holidayView = new ItemView(500); // Limit data to only necesary components holidayView.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Categories); FindItemsResults<Item> items = service.FindItems(WellKnownFolderName.Calendar, filter, holidayView); if (items.TotalCount > 0) { List<ItemId> ids = new List<ItemId>(); foreach (Item item in items) { ids.Add(item.Id); } service.DeleteItems(ids, DeleteMode.MoveToDeletedItems, SendCancellationsMode.SendToNone, AffectedTaskOccurrence.AllOccurrences); Console.WriteLine("Removed " + items.TotalCount + " holidays in the Calendar folder for " + mailbox); DateTime now = DateTime.Now; log.WriteLine(now + " - Removed " + items.TotalCount + " holidays in the Calendar folder for " + mailbox); } else { Console.WriteLine("Could not find any holidays for mailbox: " + mailbox); } } catch { log.WriteLine("Mailbox Errored: " + mailbox); rrmailboxes.Add(mailbox); } // Clear impersonation. service.ImpersonatedUserId = null; } // Rerun errored accounts. if (rrmailboxes.Count > 0) { Console.WriteLine("Looping through errored mailboxes."); } while (rrmailboxes.Count > 0) { // Run search // Current mailbox string mb = rrmailboxes.ElementAt(0); Console.WriteLine("On Mailbox: " + mb); // Take the mailbox out of the first element slot Console.WriteLine("Removing mailbox " + mb + " from beginning of rrmailboxes."); rrmailboxes.RemoveAt(0); rrmailboxes.TrimExcess(); // Find the holidays try { // Impersonate that User service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, mb); // Search String String category = "Holiday"; // Search Filter SearchFilter.IsEqualTo filter = new SearchFilter.IsEqualTo(AppointmentSchema.Categories, category); // Result Return Size, number of items ItemView holidayView = new ItemView(100); // Limit data to only necesary components holidayView.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Categories); FindItemsResults<Item> items = service.FindItems(WellKnownFolderName.Calendar, filter, holidayView); if (items.TotalCount > 0) { //Log number of found items Console.WriteLine("Found " + items.TotalCount + " holidays in the Calendar folder for " + mb); List<ItemId> ids = new List<ItemId>(); foreach (Item item in items) { ids.Add(item.Id); Console.WriteLine(mb + ": Added ItemID to be removed: " + item.Id); } service.DeleteItems(ids, DeleteMode.MoveToDeletedItems, null, null); Console.WriteLine("Removed " + items.TotalCount + " holidays in the Calendar folder for " + mb); DateTime now = DateTime.Now; log.WriteLine(now + " - Removed " + items.TotalCount + " holidays in the Calendar folder for " + mb); } else { Console.WriteLine("Could not find any holidays for mailbox: " + mb); log.WriteLine("Could not find any holidays for mailbox: " + mb); } } catch { DateTime now = DateTime.Now; log.WriteLine(now + " - Fatal Mailbox Errored: " + mb + "; Will not retry"); Console.WriteLine("Fatal Mailbox Errored: " + mb + "; Will not retry"); } // Clear impersonation. service.ImpersonatedUserId = null; } } }
/** * Function Add the Holidays **/ static void AddHolidays(ExchangeService service, List<string[]> holidays, List<string> mailboxes) { // Log file string datetimeString = DateTime.Now.ToString("MMddyyyy"); string logfile = "../../logs/" + datetimeString + "_add_holiday_log.txt"; //Initiate Error List List<string> mbs = new List<string>(); using (System.IO.StreamWriter log = new System.IO.StreamWriter(@logfile, true)) { // Loop through each email address in the passed in mailboxes List foreach (string mailbox in mailboxes) { // Impersonate that User service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, mailbox); Console.WriteLine("Attempting to Add Holidays to: " + mailbox); List<Appointment> uga_holidays = new List<Appointment>(); // Loop through all the holidays foreach (string[] holiday in holidays) { //Create a new appointment Appointment appointment = new Appointment(service); // Set details appointment.Subject = holiday[0]; appointment.Start = DateTime.Parse(holiday[1]); appointment.End = appointment.Start.AddDays(1); appointment.IsAllDayEvent = true; StringList categories = new Microsoft.Exchange.WebServices.Data.StringList(); categories.Add("Holiday"); appointment.Categories = categories; appointment.IsReminderSet = false; uga_holidays.Add(appointment); } // Save and Send try { service.CreateItems(uga_holidays, WellKnownFolderName.Calendar, MessageDisposition.SaveOnly, SendInvitationsMode.SendToNone); Console.WriteLine("Added Holiday Successfully to: " + mailbox); DateTime now = DateTime.Now; log.WriteLine(now + " - Added holidays succesfully to Mailbox: " + mailbox); } catch (Exception ex) { Console.WriteLine("Error During Initial Add - Mailbox: " + mailbox + "; Exception thrown: " + ex); log.WriteLine("Error During Initial Add - Mailbox: " + mailbox + "; Exception thrown: " + ex); mbs.Add(mailbox); } // Clear impersonation. service.ImpersonatedUserId = null; } //Process Rerun List if (mbs.Count > 0) { Console.WriteLine("Looping through re-run mailboxes."); while (mbs.Count > 0) { // Current mailbox string mb = mbs.ElementAt(0); Console.WriteLine("On Mailbox: " + mb); // Take the mailbox out of the first element slot log.WriteLine("Removing mailbox " + mb + " from beginning of mbs."); mbs.RemoveAt(0); mbs.TrimExcess(); try { // Reruns: Removes // Run search // Impersonate that User service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, mb); // Search String String category = "Holiday"; // Search Filter SearchFilter.IsEqualTo filter = new SearchFilter.IsEqualTo(AppointmentSchema.Categories, category); // Result Return Size, number of items ItemView holidayView = new ItemView(100); // Limit data to only necesary components holidayView.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Categories); FindItemsResults<Item> items = service.FindItems(WellKnownFolderName.Calendar, filter, holidayView); if (items.TotalCount > 0) { Console.WriteLine("Removing " + items.TotalCount + " holidays from " + mb); log.WriteLine("Found " + items.TotalCount + " holidays in the Calendar folder for " + mb + " to be removed."); List<ItemId> ids = new List<ItemId>(); foreach (Item item in items) { ids.Add(item.Id); } service.DeleteItems(ids, DeleteMode.MoveToDeletedItems, null, null); } else { log.WriteLine("Found no holidays in the Calendar folder for " + mb + " to be removed."); } // Rerun: Adds List<Appointment> holidays = new List<Appointment>(); // Loop through all the holidays foreach (string[] holiday in holidays) { //Create a new appointment Appointment appointment = new Appointment(service); // Set details appointment.Subject = holiday[0]; appointment.Start = DateTime.Parse(holiday[1]); appointment.End = appointment.Start.AddDays(1); appointment.IsAllDayEvent = true; StringList categories = new Microsoft.Exchange.WebServices.Data.StringList(); categories.Add("Holiday"); appointment.Categories = categories; appointment.IsReminderSet = false; holidays.Add(appointment); } service.CreateItems(holidays, null, null, SendInvitationsMode.SendToNone); Console.WriteLine("Added Holiday Successfully to" + mb); DateTime now = DateTime.Now; log.WriteLine(now + " - Added holidays succesfully to Mailbox: " + mb); } catch { log.WriteLine("Fatal Mailbox Errored on Re-Run Removes: " + mb + "; Will not retry."); Console.WriteLine("Fatal Mailbox Errored on Re-Run Removes: " + mb + "; Will not retry."); } // Clear impersonation. service.ImpersonatedUserId = null; } } } }