private async System.Threading.Tasks.Task <FolderId> FindProjectPath(Folder parentFolder, int start, int offset, string projectNumber, int recursionCount) { var view = new FolderView(int.MaxValue); view.PropertySet = new PropertySet(BasePropertySet.IdOnly, FolderSchema.DisplayName); var filter = new SearchFilter.ContainsSubstring(FolderSchema.DisplayName, projectNumber); var results = await System.Threading.Tasks.Task.Run(() => { return(this.GetEmailService.FindFolders(parentFolder.Id, filter, view)); }); //var folders = parentFolder.FindFolders(filter, view); if (results.Folders.Count <= 0) { //return await this.FindProjectPath(parentFolder, offset, offset + 255, projectNumber, recursionCount ++); Logger.LoggerAsync.InstanceOf.GeneralLogger.Info("FindProjectPath for {0} returned null after searching in {1}", projectNumber, parentFolder.DisplayName); return(null); } else if (recursionCount > 5) { throw new TimeoutException("recursion too deep"); } else { var projectFolder = results.Folders[0].Id; Logger.LoggerAsync.InstanceOf.GeneralLogger.Info("FindProjectPath returned a project folder {0} after searching in {1}", projectFolder.FolderName, parentFolder.DisplayName); return(projectFolder); } }
private static SearchFilter SetFilter(int intAddHours, string strKeySubject, string strSenderAddress) { //SearchFilter SearchFilter1 = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "【NA Major Impact】 【P1】 System Down"); //SearchFilter SearchFilter2 = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "【NA Major Impact】 【P2】 System Slow"); //SearchFilter SearchFilter3 = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "【Brazil Major Impact】 【P1】 System Down"); //SearchFilter SearchFilter4 = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "【Brazil Major Impact】 【P2】 System Slow"); //筛选今天的邮件 SearchFilter start = new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.DateTimeReceived, Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 00:00:00")).AddHours(intAddHours)); //SearchFilter end = new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeCreated, Convert.ToDateTime(DateTime.Now.ToString())); SearchFilter subject = new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, strKeySubject, ContainmentMode.Substring, ComparisonMode.IgnoreCase); // SearchFilter subject = new SearchFilter.ContainsSubstring SearchFilter SenderAddress = new SearchFilter.ContainsSubstring(EmailMessageSchema.From, strSenderAddress, ContainmentMode.Substring, ComparisonMode.IgnoreCase); //SearchFilter IsRead = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false); //SearchFilter.SearchFilterCollection secondLevelSearchFilterCollection1 = new SearchFilter.SearchFilterCollection(LogicalOperator.And, // start, // end); //SearchFilter.SearchFilterCollection secondLevelSearchFilterCollection2 = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, // SearchFilter1, SearchFilter2, SearchFilter3, SearchFilter4); //SearchFilter.SearchFilterCollection firstLevelSearchFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And, // secondLevelSearchFilterCollection1, // secondLevelSearchFilterCollection2); SearchFilter.SearchFilterCollection firstLevelSearchFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And, start, subject, SenderAddress); return(firstLevelSearchFilterCollection); }
/// <summary> /// Creates a search folder that finds items in the Inbox that contain the word "extended" in the subject line. /// </summary> /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param> private static void CreateASearchFolder(ExchangeService service) { // Create a new search folder. SearchFolder searchFolder = new SearchFolder(service); // Use the following search filter to get all mail in the Inbox with the word "extended" in the subject line. SearchFilter.ContainsSubstring searchCriteria = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "extended"); searchFolder.SearchParameters.RootFolderIds.Add(WellKnownFolderName.Inbox); searchFolder.SearchParameters.Traversal = SearchFolderTraversal.Shallow; searchFolder.SearchParameters.SearchFilter = searchCriteria; searchFolder.DisplayName = "Extended"; try { // This call results in a CreateFolder operation call to EWS. The search folder should be added // to the WellKnownFolderName.SearchFolders folder so that it is visible to clients like Outlook. searchFolder.Save(WellKnownFolderName.SearchFolders); Console.WriteLine("Added: {0}", searchFolder.DisplayName); } catch (ServiceResponseException e) { if (e.Response.ErrorCode == ServiceError.ErrorFolderExists) { Console.WriteLine("Rename your search folder or delete the existing search folder of the same name."); } else { Console.WriteLine("Error - " + e.Message); } } }
private FindFoldersResults FindSubFolder(Queue <string> folderNames, FolderId folder = null) { string folderName = folderNames.Dequeue(); FolderView folderView = new FolderView(int.MaxValue); SearchFilter searchFilter = new SearchFilter.ContainsSubstring(FolderSchema.DisplayName, folderName); FindFoldersResults folderResults; if (folder == null) { folderResults = Service.FindFolders(WellKnownFolderName.PublicFoldersRoot , searchFilter, folderView); } else { folderResults = Service.FindFolders(folder , searchFilter, folderView); } if (!folderResults.Any()) { throw new ApplicationException("Non trovata la cartella " + folderName); } if (folderNames.Any()) { return(FindSubFolder(folderNames, folderResults.Folders.First().Id)); } else { return(folderResults); } }
//gavdcodeend 06 //gavdcodebegin 07 static void UpdateOneFolder(ExchangeService ExService) { Folder rootFolder = Folder.Bind(ExService, WellKnownFolderName.Drafts); rootFolder.Load(); SearchFilter.ContainsSubstring subjectFilter = new SearchFilter.ContainsSubstring( FolderSchema.DisplayName, "my custom folder", ContainmentMode.Substring, ComparisonMode.IgnoreCase); FolderId myFolderId = null; foreach (Folder oneFolder in rootFolder.FindFolders( subjectFilter, new FolderView(1))) { myFolderId = oneFolder.Id; } Folder folderToUpdate = Folder.Bind(ExService, myFolderId); folderToUpdate.DisplayName = "New Folder Name"; folderToUpdate.Update(); }
public Folder GetFolder(string displayName) { FolderView folderView = new FolderView(int.MaxValue) { Traversal = FolderTraversal.Shallow }; if (displayName == "Inbox") { this.txtLog.Text += "EWS API: Folder.Bind\r\nLocation:..\\EWS\\EWS\\Form1.cs(60)\r\n\r\n"; return(Folder.Bind(service, WellKnownFolderName.Inbox)); } else { SearchFilter.ContainsSubstring filter = new SearchFilter.ContainsSubstring(FolderSchema.DisplayName, displayName, ContainmentMode.FullString, ComparisonMode.IgnoreCase); FindFoldersResults findFoldersResults = service.FindFolders(WellKnownFolderName.Inbox, filter, new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep }); this.txtLog.Text += "EWS API: FindFolders\r\nLocation:..\\EWS\\EWS\\Form1.cs(64)\r\n\r\n"; if (findFoldersResults.Count() > 0) { return(findFoldersResults.First()); } else { return(null); } } }
/// <summary> /// Create a search filter for filtering items based on a property that contains a specified string. /// </summary> /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param> private static void UseContainsSubstringSearchFilter(ExchangeService service) { // The ContainsSubstring filter determines whether a string exists in a string value property. // This filter instance filters on the Subject property, where the subject contains the string "Tennis Lesson". SearchFilter.ContainsSubstring containsSubstring = new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, "Tennis Lesson", ContainmentMode.ExactPhrase, ComparisonMode.Exact); // Create a nonpaged view. ItemView view = new ItemView(10); view.PropertySet = new PropertySet(EmailMessageSchema.Subject); try { FindItemsResults <Item> results = service.FindItems(WellKnownFolderName.Inbox, containsSubstring, view); foreach (Item item in results.Items) { Console.WriteLine("Subject: {0}", item.Subject); } } catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); } }
/// <summary> /// Gets first found appointment with specific subject starting from specific date. /// </summary> /// <param name="service">Exchange service.</param> /// <param name="subject">Subject of appointment to search.</param> /// <param name="start">Start date.</param> /// <returns>Found appointment if any.</returns> public static Appointment GetAppointmentBySubject(ExchangeService service, string subject, DateTime start) { Appointment meeting = null; var itemView = new ItemView(3) { PropertySet = new PropertySet(ItemSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.AppointmentType) }; // Find appointments by subject. var substrFilter = new SearchFilter.ContainsSubstring(ItemSchema.Subject, subject); var startFilter = new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, start); var filterList = new List <SearchFilter> { substrFilter, startFilter }; var calendarFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, filterList); var results = service.FindItems(WellKnownFolderName.Calendar, calendarFilter, itemView); if (results.Items.Count == 1) { meeting = results.Items[0] as Appointment; } return(meeting); }
public FolderId GetOutlookProjectPath(Entity.Store store) { //find the program folder first then search it for the project folder var parentView = new FolderView(int.MaxValue); parentView.PropertySet = new PropertySet(BasePropertySet.IdOnly, FolderSchema.DisplayName); var programNumber = Configuration.ConfigHandler.InstanceOf.ProgramMappings.Where( x => x.Value.Equals(store.Program)) .Select(y => y.Key).Distinct(); var taskResult = new System.Collections.Generic.List <System.Threading.Tasks.Task <FolderId> >(); foreach (var element in programNumber) { var filter = new SearchFilter.ContainsSubstring(FolderSchema.DisplayName, element.ToString("D2") + " "); var result = this.GetEmailService.FindFolders(WellKnownFolderName.PublicFoldersRoot, filter, parentView); var programFolder = result.Where(y => typeof(Microsoft.Exchange.WebServices.Data.ContactsFolder) != y.GetType()); taskResult.Add(this.FindProjectPath(programFolder.First(), 0, 255, "(" + store.ProjectNumber.ToString("D7") + ")", 0)); } var asyncResults = System.Threading.Tasks.Task.WhenAll(taskResult); var folders = asyncResults.Result; return(folders.Single(x => x != null)); }
//gavdcodeend 08 //gavdcodebegin 10 static void HideOneFolder(ExchangeService ExService) { Folder rootFolder = Folder.Bind(ExService, WellKnownFolderName.JunkEmail); rootFolder.Load(); SearchFilter.ContainsSubstring subjectFilter = new SearchFilter.ContainsSubstring( FolderSchema.DisplayName, "my custom folder", ContainmentMode.Substring, ComparisonMode.IgnoreCase); FolderId myFolderId = null; foreach (Folder oneFolder in rootFolder.FindFolders( subjectFilter, new FolderView(1))) { myFolderId = oneFolder.Id; } ExtendedPropertyDefinition isHiddenProp = new ExtendedPropertyDefinition(0x10f4, MapiPropertyType.Boolean); PropertySet propSet = new PropertySet(isHiddenProp); Folder folderToHide = Folder.Bind(ExService, myFolderId, propSet); folderToHide.SetExtendedProperty(isHiddenProp, true); folderToHide.Update(); }
public FolderId GetProjectRfiFolder(FolderId folderId) { var folder = Folder.Bind(this.GetEmailService, folderId, new PropertySet(BasePropertySet.IdOnly, FolderSchema.DisplayName)); var folderView = new FolderView(int.MaxValue); folderView.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Categories); var filter = new SearchFilter.ContainsSubstring(FolderSchema.DisplayName, "RFI"); var result = folder.FindFolders(filter, folderView); return(result.Folders[0].Id); }
/// <summary> /// This method gets the contacts that have the special DisplayName and property /// definitions in the special folder. /// </summary> private static List <Contact> GetContacts(Folder contactsFolder, String name, params PropertyDefinition[] schemas) { if (contactsFolder == null) { return(null); } List <Contact> contacts = new List <Contact>(); SearchFilter.SearchFilterCollection filters = new SearchFilter.SearchFilterCollection(LogicalOperator.And); if (!String.IsNullOrWhiteSpace(name)) { SearchFilter searchFilter = new SearchFilter.ContainsSubstring(ContactSchema.DisplayName, name); filters.Add(searchFilter); } if (schemas != null) { foreach (PropertyDefinition schema in schemas) { SearchFilter searchFilter = new SearchFilter.Exists(schema); filters.Add(searchFilter); } } const Int32 pageSize = 10; ItemView itemView = new ItemView(pageSize); PropertySet propertySet = new PropertySet(BasePropertySet.IdOnly, schemas); propertySet.Add(ContactSchema.DisplayName); itemView.PropertySet = propertySet; FindItemsResults <Item> findResults = null; do { findResults = contactsFolder.FindItems(filters, itemView); itemView.Offset += pageSize; contacts.AddRange(findResults.Cast <Contact>()); } while (findResults.MoreAvailable); return(contacts); }
/// <inheritdoc /> protected override void Execute(CodeActivityContext context) { var service = ExchangeHelper.GetService(context.GetValue(OrganizerPassword), context.GetValue(ExchangeUrl), context.GetValue(OrganizerEmail)); var start = context.GetValue(AppointmentDateFrom); var appointmentSubject = context.GetValue(AppointmentSubject); var amount = context.GetValue(Amount); var itemView = new ItemView(amount) { PropertySet = new PropertySet( ItemSchema.Subject, AppointmentSchema.Start, ItemSchema.DisplayTo, AppointmentSchema.AppointmentType, ItemSchema.DateTimeSent) }; // Find appointments by subject. var substrFilter = new SearchFilter.ContainsSubstring(ItemSchema.Subject, appointmentSubject); var startFilter = new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, start); var filterList = new List <SearchFilter> { substrFilter, startFilter }; var calendarFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, filterList); var results = service.FindItems(WellKnownFolderName.SentItems, calendarFilter, itemView); var history = results.Select(item => new NotifyHistory { Subject = item.Subject, SentOn = item.DateTimeSent, SentTo = item.DisplayTo }).ToArray(); context.SetValue(SentNotificationsHistory, history); }
/// <summary> /// Find items having a ExtendedPropertyDefinition 0x36 /// </summary> /// <param name="MailboxFolder">The mailbox folder to search</param> /// <returns>Items of an item search operation</returns> public static List <Item> PrivateItems(Folder MailboxFolder, string Subject) { int pageSize = 100; int pageOffset = 0; bool moreItems = true; var resultItems = new List <Item>(); var extendedPropertyDefinition = new ExtendedPropertyDefinition(0x36, MapiPropertyType.Integer); SearchFilter searchFilter = new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, Subject); var view = new ItemView(pageSize, pageOffset); view.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.Sensitivity, ItemSchema.Subject, extendedPropertyDefinition); view.Traversal = ItemTraversal.Shallow; while (moreItems) { try { findResults = MailboxFolder.FindItems(searchFilter, view); moreItems = findResults.MoreAvailable; foreach (var Found in findResults) { resultItems.Add(Found); } // if more folders than the offset is aviable we need to page if (moreItems) { view.Offset += pageSize; } } catch (Exception ex) { log.Error("Failed to fetch items.", ex); moreItems = false; Environment.Exit(3); } } return(resultItems); }
private void btnGetCalendarList_Click(object sender, EventArgs e) { Folder root = Folder.Bind(service, WellKnownFolderName.Root); SearchFilter.ContainsSubstring filter = new SearchFilter.ContainsSubstring(FolderSchema.FolderClass, "IPF.Appointment", ContainmentMode.Substring, ComparisonMode.IgnoreCase); FindFoldersResults findFoldersResults = root.FindFolders(filter, new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep }); this.listViewCalendar.View = View.Details; this.listViewCalendar.Items.Clear(); foreach (var item in findFoldersResults) { var listViewItem = new ListViewItem(new[] { item.Id.UniqueId, item.DisplayName }); this.listViewCalendar.Items.Add(listViewItem); } this.listViewCalendar.Items[0].Selected = true; initialListViewCalendarMeeting(this.listViewCalendar.Items[0].Text); }
public void ForwardedAppointmentTest() { DateTime.TryParse("06-July-2019", out var testStartDate); var service = ExchangeHelper.GetService(ExchangePass, ExchangeServerUrl, ExchangeLogin); var itemView = new ItemView(10) { PropertySet = new PropertySet(ItemSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.AppointmentType) }; // Find appointments by subject. var substrFilter = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "AppointmentAttachmentCheck1"); var startFilter = new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, testStartDate); var filterList = new List <SearchFilter> { substrFilter, startFilter }; var calendarFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, filterList); var results = service.FindItems(WellKnownFolderName.SentItems, calendarFilter, itemView); foreach (var cur in results) { var item = Item.Bind(service, cur.Id, new PropertySet(ItemSchema.Subject, AppointmentSchema.Start, ItemSchema.DisplayTo, AppointmentSchema.AppointmentType, ItemSchema.DateTimeSent)); var displayTo = item.DisplayTo; Console.WriteLine(displayTo); Console.WriteLine(item.DateTimeSent); } Assert.AreEqual("AppointmentAttachmentCheck1", "AppointmentAttachmentCheck1"); }
//gavdcodeend 07 //gavdcodebegin 08 static void EmptyOneFolder(ExchangeService ExService) { Folder rootFolder = Folder.Bind(ExService, WellKnownFolderName.Drafts); rootFolder.Load(); SearchFilter.ContainsSubstring subjectFilter = new SearchFilter.ContainsSubstring( FolderSchema.DisplayName, "new folder name", ContainmentMode.Substring, ComparisonMode.IgnoreCase); FolderId myFolderId = null; foreach (Folder oneFolder in rootFolder.FindFolders( subjectFilter, new FolderView(1))) { myFolderId = oneFolder.Id; } Folder folderToEmpty = Folder.Bind(ExService, myFolderId); folderToEmpty.Empty(DeleteMode.HardDelete, true); }
public EmailMessage GetVpnEmail(ExchangeService client, string emailSubjectPrefix, string inboxSubFolderNameWithVpnEmails = null) { Folder vpnFolder = GetVpnFolder(client, inboxSubFolderNameWithVpnEmails); // Searching emails into a specific folder: // FindItemsResults<Item> emailsInVpnFolder = client.FindItems("MyEmailFolder", subjectFilter, folderView); // This throws an exception, the folder ID is not the folder name but some kind of GUID, throws exception. // https://docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-use-search-filters-with-ews-in-exchange var subjectFilterBySubject = new SearchFilter.ContainsSubstring(ItemSchema.Subject, $"{emailSubjectPrefix}", ContainmentMode.Substring, ComparisonMode.IgnoreCase); var searchFilterUnread = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false); var searchFilterRecentDate = new SearchFilter.IsGreaterThan(EmailMessageSchema.DateTimeReceived, DateTime.UtcNow.AddMinutes(-30)); var searchFilterNewVpnCode = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterUnread, subjectFilterBySubject, searchFilterRecentDate); var emailView = new ItemView(pageSize: 5); var vpnEmails = vpnFolder.FindItems(searchFilterNewVpnCode, emailView).OrderByDescending(e => e.DateTimeSent); var mostRecentVpnEmailItem = vpnEmails.FirstOrDefault(); if (mostRecentVpnEmailItem?.Id == null) { return(null); } var mostRecentVpnEmailMessage = EmailMessage.Bind(client, mostRecentVpnEmailItem.Id); return(mostRecentVpnEmailMessage); }
public void Execute(IActivityRequest request, IActivityResponse response) { userName = settings.UserName; password = settings.Password; domain = settings.Domain; serviceURL = settings.ServiceUrl; exchangeVersion = settings.ExchangeVersion; SearchField = request.Inputs["Search Field"].AsString(); SearchString = request.Inputs["Search String"].AsString(); SearchAlgorithm = request.Inputs["Search Algorithm"].AsString(); folderName = request.Inputs["Folder Name"].AsString(); string alternateMailbox = string.Empty; if (request.Inputs.Contains("Alternate Mailbox")) { alternateMailbox = request.Inputs["Alternate Mailbox"].AsString(); } FolderId folderID = new FolderId(WellKnownFolderName.Inbox); ExchangeService service = new ExchangeService(); switch (exchangeVersion) { case "Exchange2007_SP1": service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); break; case "Exchange2010": service = new ExchangeService(ExchangeVersion.Exchange2010); break; case "Exchange2010_SP1": service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); break; default: service = new ExchangeService(); break; } service.Credentials = new WebCredentials(userName, password, domain); String AccountUrl = userName + "@" + domain; if (serviceURL.Equals("Autodiscover")) { service.AutodiscoverUrl(AccountUrl, (a) => { return(true); }); } else { service.Url = new Uri(serviceURL); } if (!alternateMailbox.Equals(String.Empty)) { service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, alternateMailbox); } if (!folderName.Equals(String.Empty)) { SearchFilter folderFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, folderName); FolderView folderView = new FolderView(int.MaxValue); folderView.PropertySet = new PropertySet(BasePropertySet.IdOnly); folderView.PropertySet.Add(FolderSchema.DisplayName); folderView.Traversal = FolderTraversal.Deep; FindFoldersResults results = service.FindFolders(WellKnownFolderName.MsgFolderRoot, folderFilter, folderView); foreach (Folder folder in results) { folderID = folder.Id; break; } } ItemView emailView = new ItemView(int.MaxValue); SearchFilter EmailFilter = new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, SearchString); switch (SearchField) { case "Subject": switch (SearchAlgorithm) { case "Equals": EmailFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.Subject, SearchString); break; case "Contains String": EmailFilter = new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, SearchString); break; case "Does Not Equal": EmailFilter = new SearchFilter.IsNotEqualTo(EmailMessageSchema.Subject, SearchString); break; } break; case "From": switch (SearchAlgorithm) { case "Equals": EmailFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.From, SearchString); break; case "Contains String": EmailFilter = new SearchFilter.ContainsSubstring(EmailMessageSchema.From, SearchString); break; case "Does Not Equal": EmailFilter = new SearchFilter.IsNotEqualTo(EmailMessageSchema.From, SearchString); break; } break; default: switch (SearchAlgorithm) { case "Equals": EmailFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.Subject, SearchString); break; case "Contains String": EmailFilter = new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, SearchString); break; case "Does Not Equal": EmailFilter = new SearchFilter.IsNotEqualTo(EmailMessageSchema.Subject, SearchString); break; } break; } FindItemsResults <Item> findResults = service.FindItems(folderID, EmailFilter, emailView); response.Publish("Number of Results", findResults.Items.Count.ToString()); response.WithFiltering().PublishRange(getMail(findResults, service)); }
/// <summary> /// This method creates and sets the search folder. /// </summary> private static SearchFolder CreateSearchFolder(ExchangeService service, Dictionary <PropertyDefinition, String> filters, String displayName) { if (service == null) { return(null); } SearchFilter.SearchFilterCollection filterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And); // We only search the nearest 30 days emails. DateTime startDate = DateTime.Now.AddDays(-30); DateTime endDate = DateTime.Now; SearchFilter startDateFilter = new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.DateTimeCreated, startDate); SearchFilter endDateFilter = new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeCreated, endDate); filterCollection.Add(startDateFilter); filterCollection.Add(endDateFilter); SearchFilter itemClassFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.ItemClass, "IPM.Note"); filterCollection.Add(itemClassFilter); // Set the other filters. if (filters != null) { foreach (PropertyDefinition property in filters.Keys) { SearchFilter searchFilter = new SearchFilter.ContainsSubstring(property, filters[property]); filterCollection.Add(searchFilter); } } FolderId folderId = new FolderId(WellKnownFolderName.Inbox); Boolean isDuplicateFoler = true; SearchFilter duplicateFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, displayName); SearchFolder searchFolder = GetFolder(service, duplicateFilter, WellKnownFolderName.SearchFolders) as SearchFolder; // If there isn't the specific search folder, we create a new one. if (searchFolder == null) { searchFolder = new SearchFolder(service); isDuplicateFoler = false; } searchFolder.SearchParameters.RootFolderIds.Add(folderId); searchFolder.SearchParameters.Traversal = SearchFolderTraversal.Shallow; searchFolder.SearchParameters.SearchFilter = filterCollection; if (isDuplicateFoler) { searchFolder.Update(); } else { searchFolder.DisplayName = displayName; searchFolder.Save(WellKnownFolderName.SearchFolders); } return(searchFolder); }
private void ExchangeSync(ExchangeService service, ExchangeTraceListener trace) { bool IsSynced = false; Status = EProviderStatus.Syncronizing; do { try { ItemView itemView = new ItemView(int.MaxValue) { PropertySet = new PropertySet(BasePropertySet.IdOnly) }; itemView.PropertySet.Add(ItemSchema.DateTimeReceived); itemView.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending); FolderView folderView = new FolderView(int.MaxValue) { PropertySet = new PropertySet(BasePropertySet.IdOnly), Traversal = FolderTraversal.Deep }; folderView.PropertySet.Add(FolderSchema.WellKnownFolderName); SearchFilter.IsEqualTo f1 = new SearchFilter.IsEqualTo(EmailMessageSchema.From, new EmailAddress(ApplicationSettings.EmailRecipients.FDLSystem)); // In order to import FDL and EA files, the only way is to work around the "from" address check. // To do this we check if in the recipient fdl_chk is present and, at a later time, we will check if the sender is the FDL System SearchFilter.ContainsSubstring f2 = new SearchFilter.ContainsSubstring(ItemSchema.DisplayTo, ApplicationSettings.EmailRecipients.FDL_CHK_Display, ContainmentMode.Substring, ComparisonMode.IgnoreCase); SearchFilter.SearchFilterCollection compoundFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, f1, f2); lock (service) { foreach (Item item in FindItemsInSubfolders(service, new FolderId(WellKnownFolderName.MsgFolderRoot), compoundFilter, folderView, itemView)) { if (exitToken.IsCancellationRequested) { break; } if (!(item is EmailMessage)) { continue; } EmailMessage message = EmailMessage.Bind(service, item.Id); // Double check in order to avoiding wrong fdl import (bugfix check the commment above) if (message.From.Address.ToLower() == ApplicationSettings.EmailRecipients.FDLSystem.ToLower()) { NotifyNewMessage(message); } } } IsSynced = true; Status = EProviderStatus.Syncronized; } catch (Exception ex) { if (trace.Result == ETraceResult.LoginError) { Status = EProviderStatus.LoginError; return; } else { Wait(ApplicationSettings.General.WaitForNextConnectionRetry); } } } while (!IsSynced && !exitToken.IsCancellationRequested); }
// Go connect to afolder and get the items public static List <Item> GetItems(ExchangeService service, string strFolder) { Folder fld = null; int iOffset = 0; int iPageSize = 500; bool bMore = true; List <Item> lItems = new List <Item>(); FindItemsResults <Item> findResults = null; DateTime dtNow = DateTime.Now; DateTime dtBack = dtNow.AddHours(-24); if (bStartDate) // default is 24 hours ago on the date, but the user can specify longer ago than that if they wish. { dtBack = dtStartDate; } SearchFilter.ContainsSubstring apptFilter = new SearchFilter.ContainsSubstring(ItemSchema.ItemClass, "IPM.Appointment"); SearchFilter.IsGreaterThanOrEqualTo modifiedFilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.LastModifiedTime, dtBack); SearchFilter.SearchFilterCollection multiFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, apptFilter, modifiedFilter); if (strFolder == "Calendar") { try { // Here's where it connects to the Calendar fld = Folder.Bind(service, WellKnownFolderName.Calendar, new PropertySet()); fldCal = fld; } catch (ServiceResponseException ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(""); Console.WriteLine("Could not connect to this user's mailbox or Calendar folder."); Console.WriteLine(ex.Message); Console.ResetColor(); return(null); } } else if (strFolder == "Purges") { try { // Here's where it connects to Purges fld = Folder.Bind(service, WellKnownFolderName.RecoverableItemsPurges, new PropertySet()); fldPurges = fld; } catch (ServiceResponseException ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(""); Console.WriteLine("Could not connect to this user's mailbox or Purges folder."); Console.WriteLine(ex.Message); Console.ResetColor(); return(null); } } else { Console.WriteLine("Not Purges or Calendar - no connection."); return(null); } // if we're in then we get here // creating a view with props to request / collect ItemView cView = new ItemView(iPageSize, iOffset, OffsetBasePoint.Beginning); List <ExtendedPropertyDefinition> propSet = new List <ExtendedPropertyDefinition>(); DoProps(ref propSet); cView.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties); foreach (PropertyDefinitionBase pdbProp in propSet) { cView.PropertySet.Add(pdbProp); } if (strFolder == "Purges") { cView.OrderBy.Add(ItemSchema.LastModifiedTime, SortDirection.Descending); while (bMore) { findResults = fld.FindItems(multiFilter, cView); foreach (Item item in findResults.Items) { lItems.Add(item); } bMore = findResults.MoreAvailable; if (bMore) { cView.Offset += iPageSize; } } } else // Calendar folder - don't need to do the search filtering here... { while (bMore) { findResults = fld.FindItems(cView); foreach (Item item in findResults.Items) { lItems.Add(item); } bMore = findResults.MoreAvailable; if (bMore) { cView.Offset += iPageSize; } } } return(lItems); }
static void Main(string[] args) { var cmdLineArgs = new CMDLINEARGS(); if (args.Length == 0 || args[0][1] == '?' || args[0][1] == 'H' || args[0][1] == 'h') { DisplayUsage(); return; } cmdLineArgs.Server = args[0]; cmdLineArgs.EwsUrl = String.Format("https://{0}/ews/exchange.asmx", cmdLineArgs.Server);; g_svcObject = new ExchangeService(ExchangeVersion.Exchange2013_SP1); if (args.Length > 3) { if (!String.IsNullOrEmpty(args[1])) { cmdLineArgs.username = args[1]; } if (!String.IsNullOrEmpty(args[2])) { cmdLineArgs.password = args[2]; } if (!String.IsNullOrEmpty(args[3])) { cmdLineArgs.domain = args[3]; } if (!String.IsNullOrEmpty(cmdLineArgs.username) && !String.IsNullOrEmpty(cmdLineArgs.password)) { g_svcObject.Credentials = new WebCredentials(cmdLineArgs.username, cmdLineArgs.password, cmdLineArgs.domain); } } else { DisplayUsage(); } if (String.IsNullOrEmpty(cmdLineArgs.username) && String.IsNullOrEmpty(cmdLineArgs.password) && String.IsNullOrEmpty(cmdLineArgs.domain)) { g_svcObject.UseDefaultCredentials = true; g_svcObject.Credentials = null; } if (args.Length > 4) { cmdLineArgs.TargetSubject = args[4]; } // I guess we should do the right thing and default to false. cmdLineArgs.AcceptSslCheck = false; if (args.Length > 5) { switch (args[5][0]) { case '1': case 't': cmdLineArgs.AcceptSslCheck = true; break; } } ServicePointManager.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return(cmdLineArgs.AcceptSslCheck); }; g_svcObject.Url = new System.Uri(cmdLineArgs.EwsUrl); g_svcObject.TraceEnabled = true; g_svcObject.TraceFlags = TraceFlags.All; var itemView = new ItemView(50); itemView.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject); itemView.Traversal = ItemTraversal.Shallow; var searchFilter = new SearchFilter.ContainsSubstring(ItemSchema.Subject, cmdLineArgs.TargetSubject); var items = g_svcObject.FindItems(WellKnownFolderName.Inbox, searchFilter, itemView); if (items.TotalCount != 1) { if (items.TotalCount == 0) { Console.WriteLine("Found few items. Confirm the search terms are correct!"); } else { Console.WriteLine("Found too many items. Confirm the search terms are correct!"); } return; } var msg = items.Items[0]; var rtfCompressed = new ExtendedPropertyDefinition(0x1009, MapiPropertyType.Binary); msg.Load(new PropertySet(BasePropertySet.FirstClassProperties, rtfCompressed, ItemSchema.Attachments)); //var fileAttach = msg.Attachments[0]; var newMsg = new EmailMessage(g_svcObject); newMsg.Subject = "RE: " + msg.Subject; newMsg.SetExtendedProperty(rtfCompressed, msg.ExtendedProperties[0].Value); if (msg.Attachments.Count > 0) { FileAttachment fileAttachment = msg.Attachments[0] as FileAttachment; fileAttachment.Load(); var newAttachment = newMsg.Attachments.AddFileAttachment(fileAttachment.Name, fileAttachment.Content); newAttachment.IsInline = newAttachment.IsInline; newAttachment.IsContactPhoto = fileAttachment.IsContactPhoto; } newMsg.Save(); }
private void setupSchemaFiltering(SearchFilter.SearchFilterCollection EmailfilterCollection) { if (SearchAlgorithm.HasValue) { SearchFilter EmailFilter; switch (SearchAlgorithm) { case SearchAlgorithmOptions.Equals: switch (SearchField) { case SearchFieldOptions.Body: EmailFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.Body, SearchString); break; case SearchFieldOptions.From: EmailFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.From, SearchString); break; case SearchFieldOptions.Subject: default: EmailFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.Subject, SearchString); break; } break; case SearchAlgorithmOptions.DoesNotEqual: switch (SearchField) { case SearchFieldOptions.Body: EmailFilter = new SearchFilter.IsNotEqualTo(EmailMessageSchema.Body, SearchString); break; case SearchFieldOptions.From: EmailFilter = new SearchFilter.IsNotEqualTo(EmailMessageSchema.From, SearchString); break; case SearchFieldOptions.Subject: default: EmailFilter = new SearchFilter.IsNotEqualTo(EmailMessageSchema.Subject, SearchString); break; } break; case SearchAlgorithmOptions.ContainsString: default: switch (SearchField) { case SearchFieldOptions.Body: EmailFilter = new SearchFilter.ContainsSubstring(EmailMessageSchema.Body, SearchString); break; case SearchFieldOptions.From: EmailFilter = new SearchFilter.ContainsSubstring(EmailMessageSchema.From, SearchString); break; case SearchFieldOptions.Subject: default: EmailFilter = new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, SearchString); break; } break; } EmailfilterCollection.Add(EmailFilter); } }
public static void DownloadAttachement(string mailaddress, string subject, string outfolder, string logFile, bool logVerbose) { ExchangeService exservice = new ExchangeService(ExchangeVersion.Exchange2010_SP2); exservice.UseDefaultCredentials = true; exservice.AutodiscoverUrl(mailaddress); FolderId folderid = new FolderId(WellKnownFolderName.Inbox, mailaddress); Folder inbox = Folder.Bind(exservice, folderid); SearchFilter.SearchFilterCollection sfcollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And); SearchFilter.IsEqualTo sfir = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false); sfcollection.Add(sfir); SearchFilter.IsEqualTo sfha = new SearchFilter.IsEqualTo(EmailMessageSchema.HasAttachments, true); sfcollection.Add(sfha); //SearchFilter.ContainsSubstring sffrm = new SearchFilter.ContainsSubstring(EmailMessageSchema.From, from); No longer needed as multiple addresses will send emails. //sfcollection.Add(sffrm); SearchFilter.IsGreaterThanOrEqualTo sfdt = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, DateTime.Now.AddDays(-31)); sfcollection.Add(sfdt); SearchFilter.ContainsSubstring sfsub = new SearchFilter.ContainsSubstring(ItemSchema.Subject, subject); sfcollection.Add(sfsub); //Initialise loop variables int pagesize = 100; int offset = 0; bool moreitems = true; //Load emails and download attachments while (moreitems) { ItemView view = new ItemView(pagesize, offset, OffsetBasePoint.Beginning); FindItemsResults <Item> finditems = inbox.FindItems(sfcollection, view); if (finditems.TotalCount > 0) { Log.message(LogEntryType.INFO, "DBAidExtractor", "Found " + finditems.TotalCount.ToString() + " mail items.", logFile); } else { Log.message(LogEntryType.INFO, "DBAidExtractor", "No more mail items found.", logFile); break; } foreach (EmailMessage item in finditems.Items) { try { item.Load(); foreach (FileAttachment attach in item.Attachments) { attach.Load(); FileStream file = null; try { file = new System.IO.FileStream(Path.Combine(outfolder, attach.Name), FileMode.Create); file.Write(attach.Content, 0, attach.Content.Length); } catch (Exception ex) { Log.message(LogEntryType.WARNING, "DBAidExtractor", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile); continue; } finally { file.Flush(); file.Close(); } Log.message(LogEntryType.INFO, "DBAidExtractor", "Downloaded Attachment:" + outfolder + "\\" + attach.Name, logFile); } item.IsRead = true; item.Update(ConflictResolutionMode.AlwaysOverwrite); } catch (Exception ex) { Log.message(LogEntryType.WARNING, "DBAidExtractor", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile); continue; } } if (finditems.MoreAvailable == false) { moreitems = false; } } }
public static void SaveEmailAttachment(ExchangeService service, string Box, string Filterstring = null) { if (Box == "SentItems") { aaaa = WellKnownFolderName.SentItems; } else { aaaa = WellKnownFolderName.Inbox; } Output(@".\inbox\log.txt", "==============================mail========================" + Box); int num = 0; //创建过滤器, 条件为邮件未读. //SearchFilter sf = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true); //查找Inbox,加入过滤器条件,结果10条 //WellKnownFolderName.Parse(WellKnownFolderName.1); ItemView view = new ItemView(999999); //-- 显示条数 SearchFilter.ContainsSubstring subjectFilter = new SearchFilter.ContainsSubstring(ItemSchema.Body, Filterstring, ContainmentMode.Substring, ComparisonMode.IgnoreCase); Folder inbox = Folder.Bind(service, aaaa); // inbox SentItems view.PropertySet = new PropertySet(BasePropertySet.IdOnly); if (Filterstring == null) { findResultsaa = inbox.FindItems(view); } else if (Filterstring != null) { findResultsaa = inbox.FindItems(subjectFilter, view); } FindItemsResults <Item> findResults = findResultsaa; foreach (Item item in findResults.Items) { num = num + 1; PropertySet props = new PropertySet(EmailMessageSchema.MimeContent, EmailMessageSchema.Subject);//这个地方设置属性 // This findResults.Items in a GetItem call to EWS. var email = EmailMessage.Bind(service, item.Id, props); string path = @".\inbox\" + Box + "\\"; if (Directory.Exists(path) == false)//如果不存在就创建file文件夹 { Directory.CreateDirectory(path); } string emlFileName = path + num + ".eml"; //Console.WriteLine(item.Id); //string mhtFileName = @"C:\tmp\item.Id.mht"; // Save as .eml. using (FileStream fs = new FileStream(emlFileName, FileMode.Create, FileAccess.Write)) { fs.Write(email.MimeContent.Content, 0, email.MimeContent.Content.Length); } Console.WriteLine(Box + "Email title name: " + email.Subject + ".eml"); Output(@".\inbox\log.txt", num + "^^^^^" + email.Subject); // Save as .mht. //using (FileStream fs = new FileStream(mhtFileName, FileMode.Create, FileAccess.Write)) //{ // fs.Write(email.MimeContent.Content, 0, email.MimeContent.Content.Length); //} } }