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); } } }
public static Contact FindContactByDisplayName(ExchangeService service, string DisplayName) { // Get the number of items in the Contacts folder. To keep the response smaller, request only the TotalCount property. ContactsFolder contactsfolder = ContactsFolder.Bind(service, WellKnownFolderName.Contacts, new PropertySet(BasePropertySet.IdOnly, FolderSchema.TotalCount)); // Set the number of items to the smaller of the number of items in the Contacts folder or 1000 int numItems = contactsfolder.TotalCount < 1000 ? contactsfolder.TotalCount : 1000; // Instantiate the item view with the number of items to retrieve from the Contacts folder. ItemView view = new ItemView(numItems); // To keep the request smaller, send only the display name. view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName); //Create a searchfilter. SearchFilter.IsEqualTo filter = new SearchFilter.IsEqualTo(ContactSchema.DisplayName, DisplayName); // Retrieve the items in the Contacts folder with the properties you've selected. FindItemsResults <Item> contactItems = service.FindItems(WellKnownFolderName.Contacts, filter, view); if (contactItems.Count() == 1) //Only one contact was found { return((Contact)contactItems.Items[0]); } else //No contacts, or more than one contact with the same DisplayName, were found. { return(null); } }
private bool CheckRoomAvailability(string roomName, string email, Slot slot, ExchangeService service, DateTime startDate, DateTime endtDate, Dictionary <string, FindItemsResults <Appointment> > fapts) { bool blnReturn = true; string key = email + startDate.ToString("ddMMyyyy") + endtDate.ToString("ddMMyyyy"); FindItemsResults <Appointment> fapt = fapts[key]; if (fapt == null) { return(false); } if (fapt.Count() > 0) { var starts = fapt.Select(t => t.Start).ToList(); var ends = fapt.Select(t => t.End).ToList(); if (fapt.Where(t => ((t.Start < slot.StartDateTime && t.End > slot.StartDateTime) || (t.Start < slot.EndDateTime && t.End > slot.EndDateTime) || (slot.StartDateTime < t.Start && slot.EndDateTime > t.Start) || (slot.StartDateTime < t.End && slot.EndDateTime > t.End) || (slot.StartDateTime == t.Start && slot.EndDateTime == t.End) )).Count() > 0) { return(false); } } return(blnReturn); }
/// <summary> /// The method will return all the tasks from "Tasks" folder /// </summary> /// <returns>List of tasks</returns> /// public FindItemsResults <Item> GetAllTasks() { // Specify the folder to search, and limit the properties returned in the result. TasksFolder tasksfolder = TasksFolder.Bind(Service, WellKnownFolderName.Tasks, new PropertySet(BasePropertySet.IdOnly, FolderSchema.TotalCount)); // Set the count of items to be displayed. int numItems = tasksfolder.TotalCount > 50 ? tasksfolder.TotalCount : 50; // Instantiate the item view with the number of items to retrieve from the required folder. ItemView view = new ItemView(numItems); // Retrieve the items in the Tasks folder. FindItemsResults <Item> taskItems = Service.FindItems(WellKnownFolderName.Tasks, view); //Load Body and other Service.LoadPropertiesForItems(taskItems, PropertySet.FirstClassProperties); if (taskItems != null && taskItems.Count() > 0) { return(taskItems); } else { return(null); } }
public static FindItemsResults<Item> RetrieveTasks() { // Specify the folder to search, and limit the properties returned in the result. TasksFolder tasksfolder = TasksFolder.Bind(service, WellKnownFolderName.Tasks, new PropertySet(BasePropertySet.FirstClassProperties, FolderSchema.TotalCount)); // Set the number of items to the smaller of the number of items in the Contacts folder or 1000. int numItems = tasksfolder.TotalCount < 1000 ? tasksfolder.TotalCount : 1000; // Instantiate the item view with the number of items to retrieve from the contacts folder. ItemView view = new ItemView(numItems); // To keep the request smaller, send only the display name. view.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties, TaskSchema.Subject); // Retrieve the items in the Tasks folder taskItems = service.FindItems(WellKnownFolderName.Tasks, view); // If the subject of the task matches only one item, return that task item. if (taskItems.Count() > 1) { service.LoadPropertiesForItems(taskItems.Items, PropertySet.FirstClassProperties); return (FindItemsResults<Item>)taskItems; } // No tasks, were found. else { return null; } }
public static Task FindTaskBySubject(ExchangeService service, string Subject) { // Specify the folder to search, and limit the properties returned in the result. TasksFolder tasksfolder = TasksFolder.Bind(service, WellKnownFolderName.Tasks, new PropertySet(BasePropertySet.IdOnly, FolderSchema.TotalCount)); // Set the number of items to the smaller of the number of items in the Contacts folder or 1000. int numItems = tasksfolder.TotalCount < 1000 ? tasksfolder.TotalCount : 1000; // Instantiate the item view with the number of items to retrieve from the contacts folder. ItemView view = new ItemView(numItems); // To keep the request smaller, send only the display name. view.PropertySet = new PropertySet(BasePropertySet.IdOnly, TaskSchema.Subject); // Create a searchfilter to check the subject of the tasks. SearchFilter.IsEqualTo filter = new SearchFilter.IsEqualTo(TaskSchema.Subject, Subject); // Retrieve the items in the Tasks folder with the properties you selected. FindItemsResults <Item> taskItems = service.FindItems(WellKnownFolderName.Tasks, filter, view); // If the subject of the task matches only one item, return that task item. if (taskItems.Count() == 1) { return((Task)taskItems.Items[0]); } // No tasks, or more than one, were found. else { return(null); } }
public List <EmailDTO> ObtenerEmails(string id, string filtro, ref int total, int num, int pagina) { EmailDTO oEmail; List <EmailDTO> oEmails = new List <EmailDTO>(); FindItemsResults <Item> fEmails = ObtenerEmails2(id, filtro, ref total, num, pagina); for (int i = 0; i < fEmails.Count(); i++) { oEmail = this.loadEmail(fEmails.ElementAt(i)); oEmails.Add(oEmail); } return(oEmails); }
public void Start() { if (!Connect())//si no se logra conectar entonces terminamos { Console.WriteLine("no fue posible conectarse."); return; } FindItemsResults <Item> findResults = service.FindItems( WellKnownFolderName.Inbox, new ItemView(10)); Console.WriteLine("Correos en Inbox: " + findResults.Count()); foreach (Item item in findResults.Items) { Procesar(item);//revision y procesamiento basico de un item. } Console.WriteLine("Terminamos."); }
/// <summary> /// Recuperar un EMAIL enviado usando un guid introducido anteriormente /// </summary> /// <remarks> /// Los servidores de correos no devuelven el identificador el correo enviado. /// Si quieres saber que correo has enviado dentro del servidor, tienes que buscarlo a posterior con otro identificador. /// </remarks> /// <param name="guid">Identificador GUID introducido</param> /// <param name="extras">Cargar propiedades del Email?</param> /// <param name="content">Cargar contenido del Email?</param> /// <returns></returns> public EmailMessage FindEmailWithGUID(string guid, bool extras = false, bool content = false) { var view = new ItemView(1); var myExtendedPropertyDefinition = new ExtendedPropertyDefinition(new Guid(guid), "GUID", MapiPropertyType.String); SearchFilter searchFilter = new SearchFilter.IsEqualTo(myExtendedPropertyDefinition, "GUID"); view.PropertySet = loadProperty(extras, content); // New PropertySet(BasePropertySet.IdOnly, myExtendedPropertyDefinition) FindItemsResults <Item> findResults = null; for (int i = 0; i <= 5; i++) { findResults = exchange.FindItems(WellKnownFolderName.SentItems, searchFilter, view); // (WellKnownFolderName.SentItems, searchFilter, view) if (findResults is object && findResults.Count() > 0) { return((EmailMessage)findResults.Items[0]); } System.Threading.Thread.Sleep(1000); // Esperar 1 segundo } return(null); }
private void GetCalendarGuids(ExchangeService service) { // Use a view to retrieve calendar events within 180 days DateTime startDate = DateTime.Now.AddDays(-180); DateTime endDate = DateTime.Now.AddDays(180); Mailbox userMailbox = new Mailbox(Resources.EWSUserMailbox); FolderId calendar = new FolderId(WellKnownFolderName.Calendar, userMailbox); CalendarView cView = new CalendarView(startDate, endDate); cView.PropertySet = new PropertySet(AppointmentSchema.ICalUid, AppointmentSchema.Organizer, AppointmentSchema.Subject, AppointmentSchema.Location, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.LegacyFreeBusyStatus, AppointmentSchema.AppointmentState, AppointmentSchema.IsCancelled); FindItemsResults <Item> items = null; items = service.FindItems(calendar, cView); // Set up a datatable to store appointments DataTable appointmentsData = new DataTable("Appointments"); // ICalUid Column DataColumn iCalUidColumn = new DataColumn(); iCalUidColumn.DataType = Type.GetType("System.String"); iCalUidColumn.ColumnName = "ICalUid"; appointmentsData.Columns.Add(iCalUidColumn); // ChangeKey Column DataColumn changeKeyColumn = new DataColumn(); changeKeyColumn.DataType = Type.GetType("System.String"); changeKeyColumn.ColumnName = "ChangeKey"; appointmentsData.Columns.Add(changeKeyColumn); // UniqueId Column DataColumn uniqueIdColumn = new DataColumn(); uniqueIdColumn.DataType = Type.GetType("System.String"); uniqueIdColumn.ColumnName = "UniqueID"; appointmentsData.Columns.Add(uniqueIdColumn); using (SqlBulkCopy bulkCopy = new SqlBulkCopy(Resources.SqlConnectionString, SqlBulkCopyOptions.KeepNulls & SqlBulkCopyOptions.KeepIdentity)) { bulkCopy.BatchSize = items.Count(); bulkCopy.DestinationTableName = "dbo.AppointmentIds"; bulkCopy.ColumnMappings.Clear(); bulkCopy.ColumnMappings.Add("ICalUid", "ICalUid"); bulkCopy.ColumnMappings.Add("ChangeKey", "ChangeKey"); bulkCopy.ColumnMappings.Add("UniqueID", "UniqueID"); foreach (Item item in items) { try { DataRow appointmentRow = appointmentsData.NewRow(); ItemId itemId = null; string iCalUid = null; item.TryGetProperty(AppointmentSchema.ICalUid, out iCalUid); if (iCalUid != null) { appointmentRow["ICalUid"] = iCalUid; } itemId = item.Id; appointmentRow["ChangeKey"] = itemId.ChangeKey; appointmentRow["UniqueID"] = itemId.UniqueId; appointmentsData.Rows.Add(appointmentRow); } catch (Exception ex) { Util.LogError("GetCalendarGuids failed with message: " + ex.Message); } } using (SqlConnection conn = new SqlConnection(Resources.SqlConnectionString)) { using (SqlCommand command = new SqlCommand(Resources.TruncateStoredProcedureName, conn) { CommandType = CommandType.StoredProcedure }) { conn.Open(); command.ExecuteNonQuery(); } } bulkCopy.WriteToServer(appointmentsData); } }
private void GetCalendarEvents(ExchangeService service) { // Use a view to retrieve calendar events within 60 days from today DateTime startDate = DateTime.Now.AddDays(-60); DateTime endDate = DateTime.Now.AddDays(60); Mailbox userMailbox = new Mailbox(Resources.EWSUserMailbox); FolderId calendar = new FolderId(WellKnownFolderName.Calendar, userMailbox); CalendarView cView = new CalendarView(startDate, endDate); cView.PropertySet = new PropertySet(AppointmentSchema.ICalUid, AppointmentSchema.Organizer, AppointmentSchema.Subject, AppointmentSchema.Location, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.LegacyFreeBusyStatus, AppointmentSchema.AppointmentState, AppointmentSchema.IsCancelled, AppointmentSchema.IsAllDayEvent); FindItemsResults <Item> items = null; items = service.FindItems(calendar, cView); // Set up a datatable to store appointments DataTable appointmentsData = new DataTable("Appointments"); // ICalUid Column DataColumn iCalUidColumn = new DataColumn(); iCalUidColumn.DataType = Type.GetType("System.String"); iCalUidColumn.ColumnName = "ICalUid"; appointmentsData.Columns.Add(iCalUidColumn); // Account name column DataColumn accountNameColumn = new DataColumn(); accountNameColumn.DataType = Type.GetType("System.String"); accountNameColumn.ColumnName = "AccountName"; appointmentsData.Columns.Add(accountNameColumn); // Subject column DataColumn subjectColumn = new DataColumn(); subjectColumn.DataType = Type.GetType("System.String"); subjectColumn.ColumnName = "Subject"; appointmentsData.Columns.Add(subjectColumn); // Location column DataColumn locationColumn = new DataColumn(); locationColumn.DataType = Type.GetType("System.String"); locationColumn.ColumnName = "Location"; appointmentsData.Columns.Add(locationColumn); // Start time column DataColumn startTimeColumn = new DataColumn(); startTimeColumn.DataType = Type.GetType("System.DateTime"); startTimeColumn.ColumnName = "StartTime"; appointmentsData.Columns.Add(startTimeColumn); // End time column DataColumn endTimeColumn = new DataColumn(); endTimeColumn.DataType = Type.GetType("System.DateTime"); endTimeColumn.ColumnName = "EndTime"; appointmentsData.Columns.Add(endTimeColumn); // Status column DataColumn statusColumn = new DataColumn(); statusColumn.DataType = Type.GetType("System.String"); statusColumn.ColumnName = "Status"; appointmentsData.Columns.Add(statusColumn); // Appointment State column DataColumn appointmentStateColumn = new DataColumn(); appointmentStateColumn.DataType = Type.GetType("System.Int32"); appointmentStateColumn.ColumnName = "AppointmentState"; appointmentsData.Columns.Add(appointmentStateColumn); // Is Cancelled Column DataColumn isCancelledColumn = new DataColumn(); isCancelledColumn.DataType = Type.GetType("System.Boolean"); isCancelledColumn.ColumnName = "IsCancelled"; appointmentsData.Columns.Add(isCancelledColumn); // Is All Day Event Column DataColumn isAllDayEventColumn = new DataColumn(); isAllDayEventColumn.DataType = Type.GetType("System.Boolean"); isAllDayEventColumn.ColumnName = "IsAllDayEvent"; appointmentsData.Columns.Add(isAllDayEventColumn); // ChangeKey Column DataColumn changeKeyColumn = new DataColumn(); changeKeyColumn.DataType = Type.GetType("System.String"); changeKeyColumn.ColumnName = "ChangeKey"; appointmentsData.Columns.Add(changeKeyColumn); // UniqueId Column DataColumn uniqueIdColumn = new DataColumn(); uniqueIdColumn.DataType = Type.GetType("System.String"); uniqueIdColumn.ColumnName = "UniqueID"; appointmentsData.Columns.Add(uniqueIdColumn); List <ResolvedEmailAddress> resolvedEmailAddresses = new List <ResolvedEmailAddress>(); int i = 0; using (SqlBulkCopy bulkCopy = new SqlBulkCopy(Resources.SqlConnectionString, SqlBulkCopyOptions.KeepNulls & SqlBulkCopyOptions.KeepIdentity)) { bulkCopy.BatchSize = items.Count(); bulkCopy.DestinationTableName = "dbo.TimeOffCalendarTemp"; bulkCopy.ColumnMappings.Clear(); bulkCopy.ColumnMappings.Add("ICalUid", "ICalUid"); bulkCopy.ColumnMappings.Add("AccountName", "AccountName"); bulkCopy.ColumnMappings.Add("Subject", "Subject"); bulkCopy.ColumnMappings.Add("Location", "Location"); bulkCopy.ColumnMappings.Add("StartTime", "StartTime"); bulkCopy.ColumnMappings.Add("EndTime", "EndTime"); bulkCopy.ColumnMappings.Add("Status", "Status"); bulkCopy.ColumnMappings.Add("AppointmentState", "AppointmentState"); bulkCopy.ColumnMappings.Add("IsCancelled", "IsCancelled"); bulkCopy.ColumnMappings.Add("IsAllDayEvent", "IsAllDayEvent"); bulkCopy.ColumnMappings.Add("ChangeKey", "ChangeKey"); bulkCopy.ColumnMappings.Add("UniqueID", "UniqueID"); foreach (Item item in items) { try { i++; DataRow appointmentRow = appointmentsData.NewRow(); EmailAddress accountName = null; ItemId itemId = null; string iCalUid, subject, location = null; DateTime startTime, endTime = new DateTime(); LegacyFreeBusyStatus status = new LegacyFreeBusyStatus(); int appointmentState; bool isCancelled, isAllDayEvent; item.TryGetProperty(AppointmentSchema.ICalUid, out iCalUid); if (iCalUid != null) { appointmentRow["ICalUid"] = iCalUid; } item.TryGetProperty(AppointmentSchema.Organizer, out accountName); if (accountName != null) { if (resolvedEmailAddresses.Where(re => re.EWSAddress == accountName.Address).Count() < 1) { NameResolutionCollection nd = service.ResolveName(accountName.Address); if (nd.Count > 0) { ResolvedEmailAddress resAddress = new ResolvedEmailAddress { EWSAddress = accountName.Address, SMTPAddress = nd[0].Mailbox.Address }; resolvedEmailAddresses.Add(resAddress); appointmentRow["AccountName"] = resAddress.SMTPAddress; } } else { ResolvedEmailAddress resAddress = resolvedEmailAddresses.First(re => re.EWSAddress == accountName.Address); appointmentRow["AccountName"] = resAddress.SMTPAddress; } } item.TryGetProperty(AppointmentSchema.Subject, out subject); if (subject != null) { appointmentRow["Subject"] = subject; } item.TryGetProperty(AppointmentSchema.Location, out location); if (location != null) { appointmentRow["Location"] = location; } item.TryGetProperty(AppointmentSchema.Start, out startTime); if (startTime != null) { appointmentRow["StartTime"] = startTime; } item.TryGetProperty(AppointmentSchema.End, out endTime); if (endTime != null) { appointmentRow["EndTime"] = endTime; } item.TryGetProperty(AppointmentSchema.LegacyFreeBusyStatus, out status); if (status != null) { appointmentRow["Status"] = status; } item.TryGetProperty(AppointmentSchema.AppointmentState, out appointmentState); appointmentRow["AppointmentState"] = appointmentState; item.TryGetProperty(AppointmentSchema.IsCancelled, out isCancelled); appointmentRow["IsCancelled"] = isCancelled; item.TryGetProperty(AppointmentSchema.IsAllDayEvent, out isAllDayEvent); appointmentRow["IsAllDayEvent"] = isAllDayEvent; itemId = item.Id; appointmentRow["ChangeKey"] = itemId.ChangeKey; appointmentRow["UniqueID"] = itemId.UniqueId; appointmentsData.Rows.Add(appointmentRow); int percentComplete = 0; if (items.Count() > 0) { percentComplete = ((i + 1) * 100 / items.Count()); } else { percentComplete = 100; } UpdateProgress(percentComplete); } catch (Exception ex) { Util.LogError("GetCalendarEvents failed with message: " + ex.Message); } } bulkCopy.WriteToServer(appointmentsData); using (SqlConnection conn = new SqlConnection(Resources.SqlConnectionString)) { using (SqlCommand command = new SqlCommand(Resources.MergeStoredProcedureName, conn) { CommandType = CommandType.StoredProcedure }) { conn.Open(); command.ExecuteNonQuery(); } } } }
/// <summary> /// Iterate through folder to get read/unread flags. /// </summary> /// <returns>Returns integer array with two elements : read and unread count.</returns> public int[] GetMailCountDetails() { try { int[] mailCounts = new int[2]; int unReadCount = 0; int readCount = 0; // Declare folder and item view. FolderView viewFolders = new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep, PropertySet = new PropertySet(BasePropertySet.IdOnly) }; ItemView viewEmails = new ItemView(int.MaxValue) { PropertySet = new PropertySet(BasePropertySet.IdOnly) }; //Create read and unread email items filters SearchFilter unreadFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false); SearchFilter readFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true); // Create folder filter. SearchFilter folderFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "AllItems"); //Find the AllItems folder FindFoldersResults inboxFolders = service.FindFolders(WellKnownFolderName.MsgFolderRoot, folderFilter, viewFolders); // If user does not have an AllItems folder then search the Inbox and Inbox sub-folders. if (inboxFolders.Count() == 0) { // Search all items in Inbox for read and unread email. FindItemsResults <Item> findUnreadResults = service.FindItems(WellKnownFolderName.Inbox, unreadFilter, viewEmails); FindItemsResults <Item> findReadResults = service.FindItems(WellKnownFolderName.Inbox, readFilter, viewEmails); unReadCount += findUnreadResults.Count(); readCount += findReadResults.Count(); //Get all Inbox sub-folders inboxFolders = service.FindFolders(WellKnownFolderName.Inbox, viewFolders); //Look for read and unread email in each Inbox sub folder foreach (Folder folder in inboxFolders.Folders) { findUnreadResults = service.FindItems(folder.Id, unreadFilter, viewEmails); findReadResults = service.FindItems(folder.Id, readFilter, viewEmails); unReadCount += findUnreadResults.Count(); readCount += findReadResults.Count(); } } // AllItems folder is avilable. else { foreach (Folder folder in inboxFolders.Folders) { FindItemsResults <Item> findUnreadResults = service.FindItems(folder.Id, unreadFilter, viewEmails); FindItemsResults <Item> findReadResults = service.FindItems(folder.Id, readFilter, viewEmails); unReadCount += findUnreadResults.Count(); readCount += findReadResults.Count(); } } // Fill count to the integer array. mailCounts[0] = readCount; mailCounts[1] = unReadCount; return(mailCounts); } catch (Exception) { throw; } }
//public IEnumerable<MailItem> FindItems(MailBoxCredentials credentials, string mailBoxName, string searchTerm) //{ // if (credentials == null // || String.IsNullOrEmpty(credentials.UserName)) // { // throw new UnauthorizedAccessException("No user to impersonate specified."); // } // var result = new List<MailItem>(); // var ewsURL = ConfigurationManager.AppSettings["ewsURL"].ToString(); // var networkDomain = ConfigurationManager.AppSettings["ewsNetworkDomain"].ToString(); // var networkUserName = ConfigurationManager.AppSettings["ewsNetworkUserName"].ToString(); // var networkPassword = ConfigurationManager.AppSettings["ewsNetworkPassword"].ToString(); // var useAutoDiscover = Boolean.Parse(ConfigurationManager.AppSettings["useAutodiscover"].ToString()); // ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallback; // var service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); // service.Credentials = new NetworkCredential(networkUserName, // networkPassword, // networkDomain); // if (useAutoDiscover) // { // service.AutodiscoverUrl(credentials.UserName, RedirectionUrlValidationCallback); // } // else // { // service.Url = new System.Uri(ewsURL); // } // service.ImpersonatedUserId = new ImpersonatedUserId { Id = credentials.UserName, // IdType = ConnectingIdType.SmtpAddress }; // var searchFilters = new Microsoft.Exchange.WebServices.Data.SearchFilter.SearchFilterCollection (LogicalOperator.Or, // new SearchFilter[5]{new SearchFilter.ContainsSubstring(EmailMessageSchema.Body, searchTerm), // new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, searchTerm), // new SearchFilter.ContainsSubstring(EmailMessageSchema.Sender, searchTerm), // new SearchFilter.ContainsSubstring(EmailMessageSchema.ToRecipients, searchTerm), // new SearchFilter.ContainsSubstring(EmailMessageSchema.Attachments, searchTerm) // }); // Folder rootFolder = Folder.Bind(service, WellKnownFolderName.MsgFolderRoot); // var folderView = new FolderView(1000); // var subFolders = rootFolder.FindFolders(folderView).Where(x => x.DisplayName.Equals(mailBoxName,StringComparison.InvariantCultureIgnoreCase)).ToList(); // try // { // rootFolder = Folder.Bind(service, WellKnownFolderName.PublicFoldersRoot); // subFolders.AddRange(rootFolder.FindFolders(folderView).Where(x => x.DisplayName.Equals(mailBoxName, StringComparison.InvariantCultureIgnoreCase))); // } // catch (Exception ex) // { // if (!EventLog.SourceExists(RESTMSExchangeService.LOG_SOURCE_NAME)) // { // EventLog.CreateEventSource(RESTMSExchangeService.LOG_SOURCE_NAME, "Application"); // } // EventLog.WriteEntry(RESTMSExchangeService.LOG_SOURCE_NAME, "Error accessing public folders: " + ex.ToString() + ex.StackTrace, EventLogEntryType.Warning); // } // var iv = new ItemView(1000); // iv.PropertySet = new PropertySet(BasePropertySet.IdOnly, // ItemSchema.Subject, // ItemSchema.DateTimeReceived); // foreach (var folder in subFolders) // { // var matches = service.FindItems(folder.Id, searchFilters, iv); // AddItems(service, matches, result); // } // try // { // Mailbox mb = new Mailbox(mailBoxName); // FolderId fid1 = new FolderId(WellKnownFolderName.Inbox, mb); // rootFolder = Folder.Bind(service, fid1); // var items = rootFolder.FindItems(iv); // service.LoadPropertiesForItems(items,new PropertySet{ ItemSchema.Attachments, ItemSchema.HasAttachments}); // SearchAttachmentContent(items); // var matches = service.FindItems(fid1, searchFilters, iv); // AddItems(service, matches, result); // } // catch (ServiceResponseException ex) // { // if (ex.Message.Contains("The specified object was not found in the store.")) // { // throw new UnauthorizedAccessException(String.Format("User {0} does not have access to Shared Mailbox {1}", credentials.UserName, mailBoxName), ex); // } // if (!EventLog.SourceExists(RESTMSExchangeService.LOG_SOURCE_NAME)) // { // EventLog.CreateEventSource(RESTMSExchangeService.LOG_SOURCE_NAME, "Application"); // } // EventLog.WriteEntry(RESTMSExchangeService.LOG_SOURCE_NAME, "Error accessing shared mailbox: " + mailBoxName + ex.ToString() + ex.StackTrace, EventLogEntryType.Warning); // } // catch (Exception ex) // { // if (!EventLog.SourceExists(RESTMSExchangeService.LOG_SOURCE_NAME)) // { // EventLog.CreateEventSource(RESTMSExchangeService.LOG_SOURCE_NAME, "Application"); // } // EventLog.WriteEntry(RESTMSExchangeService.LOG_SOURCE_NAME, "Error accessing shared mailbox: " + mailBoxName + ex.ToString() + ex.StackTrace, EventLogEntryType.Warning); // } // return result; //} //private void SearchAttachmentContent(FindItemsResults<Item> items) //{ // if (items == null) return; // foreach (var item in items) // { // if (item.HasAttachments) // { // foreach (var attachment in item.Attachments) // { // attachment.Load(); // } // } // } //} private void AddItems(ExchangeService service, FindItemsResults<Item> itemsFound, ICollection<MailItem> resultCollection, string mailBoxName, string folderName) { if (itemsFound == null || itemsFound.Count() <= 0) { return; } // service.LoadPropertiesForItems(itemsFound, new PropertySet(ItemSchema.Attachments, ItemSchema.Subject, ItemSchema.Body)); foreach (var item in itemsFound) { if (resultCollection.Any(x => x.Id == item.Id.ToString())) continue; var bodyText = item.Body.Text; if (!String.IsNullOrEmpty(bodyText)) { var doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(bodyText); var cleanText = String.Empty; foreach (var node in doc.DocumentNode.ChildNodes) { cleanText += node.InnerText; } bodyText = String.IsNullOrEmpty(cleanText) ? bodyText : cleanText; } var resultItem = new MailItem { AttachmentTitles = item.Attachments.Select(x => x.Name).ToList(), Body = bodyText, Id = item.Id.ToString(), Subject = item.Subject, FolderName = folderName, MailBoxName = mailBoxName }; //TODO:Get these mail values. resultItem.CCAddresses = new List<string> { }; resultItem.ToAddresses = new List<string> { }; resultItem.FromAddress = String.Empty; resultCollection.Add(resultItem); } }