/// <summary> /// Fecthing mails from a folder of mailbox. /// It will fetch without any filter /// </summary> /// <param name="service"></param> /// <param name="FolderName"></param> /// <param name="numberOfMails"></param> /// <param name="mailboxName"></param> /// <param name="onlyUnreadMails"></param> /// <returns></returns> static System.Collections.ObjectModel.Collection <Item> ReadMailFromFolder(ExchangeService service, String FolderName, Int32 numberOfMails, String mailboxName, bool onlyUnreadMails) { FolderView view = new FolderView(10000); view.PropertySet = new PropertySet(BasePropertySet.IdOnly); view.PropertySet.Add(FolderSchema.DisplayName); view.Traversal = FolderTraversal.Deep; Mailbox mailbox = new Mailbox(mailboxName); FindFoldersResults findFolderResults = service.FindFolders(new FolderId(WellKnownFolderName.MsgFolderRoot, mailbox), view); foreach (Folder folder in findFolderResults) { //For Folder filter if (folder.DisplayName == FolderName) { ItemView itemView = new ItemView(numberOfMails); if (onlyUnreadMails) { SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)); return((service.FindItems(folder.Id, searchFilter, itemView)).Items); } else { return((service.FindItems(folder.Id, itemView)).Items); } } } throw new Exception("Folder is not found"); }
private FindItemsResults<Item> FindItemsCurrentFolder(SearchFilter sf, ItemView itemView) { if (_currentFolder == null) return _service.FindItems(WellKnownFolderName.Inbox, sf, itemView); else return _service.FindItems(_currentFolder.Id, sf, itemView); }
public void getMails(string folderName, string keyword) { SearchFilter sf = null; FindItemsResults <Item> findResults = null; if (!string.IsNullOrEmpty(keyword)) { sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.ContainsSubstring(ItemSchema.Subject, keyword, ContainmentMode.Substring, ComparisonMode.IgnoreCase)); } if (string.IsNullOrEmpty(folderName)) { if (sf != null) { sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.ContainsSubstring(ItemSchema.Subject, keyword, ContainmentMode.Substring, ComparisonMode.IgnoreCase)); findResults = service.FindItems(WellKnownFolderName.Inbox, sf, new ItemView(10)); } else { findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10)); } } else { if (treeViewFolder.SelectedNode == null) { MessageBox.Show("Select a folder under Inbox firstly."); return; } else { FolderId folderId = new FolderId(folderName); if (sf != null) { sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.ContainsSubstring(ItemSchema.Subject, keyword, ContainmentMode.Substring, ComparisonMode.IgnoreCase)); findResults = service.FindItems(folderId, sf, new ItemView(10)); } else { findResults = service.FindItems(folderId, new ItemView(10)); } } } this.listViewMail.View = View.Details; this.listViewMail.Items.Clear(); foreach (Item item in findResults.Items) { EmailMessage em = item as EmailMessage; var listViewItem = new ListViewItem(new[] { em.Sender.Name, em.DisplayTo, item.Subject, item.DateTimeReceived.ToString(), em.Id.UniqueId, em.IsRead ? "Read" : "UnRead" }); this.listViewMail.Items.Add(listViewItem); } this.txtLog.Text += "Get mail list success\r\nEWS API:FindItems\r\nLocation:..\\EWS\\EWS\\Form1.cs line(112, 116, 132, 136)\r\n\r\n"; }
/// <summary> /// Send message from mailbox a to mailbox b /// </summary> public static void SendMessageFromMailboxAToMailboxB(ExchangeService exchangeService) { string messageSubject = Guid.NewGuid().ToString(); Message message = new Message(exchangeService); message.Subject = messageSubject; message.ToRecipients = new List <Recipient>(); message.ToRecipients.Add(new Recipient() { EmailAddress = new EmailAddress() { Address = AppConfig.MailboxB } }); message.Body = new ItemBody() { Content = "Test message", ContentType = BodyType.HTML }; message.Send(); exchangeService.MailboxId = new MailboxId(AppConfig.MailboxB); Thread.Sleep(10000); // allow some time for email to be delivered MessageView messageView = new MessageView(10); FolderId inbox = new FolderId(WellKnownFolderName.Inbox); SearchFilter subjectFilter = new SearchFilter.IsEqualTo( MessageObjectSchema.Subject, messageSubject); FindItemsResults <Item> messages = exchangeService.FindItems(inbox, subjectFilter, messageView); Assert.AreEqual(1, messages.TotalCount); Message msg = (Message)messages.Items[0]; msg.Reply("this is my reply"); Thread.Sleep(8000); // allow some time for email to be delivered subjectFilter = new SearchFilter.IsEqualTo( MessageObjectSchema.Subject, $"Re: {messageSubject}"); exchangeService.MailboxId = new MailboxId(AppConfig.MailboxA); messages = exchangeService.FindItems(inbox, subjectFilter, messageView); Assert.IsTrue(messages.TotalCount == 1); messages.Items[0].Delete(); }
/// <summary> /// 根据主题查询会议 /// </summary> /// <param name="senderAppointmentSubject"></param> /// <param name="config"></param> /// <returns></returns> public static MeetingMessage GetSenderMeeting(string senderAppointmentSubject, ExchangeAdminConfig config) { InitializeEws(config); SearchFilter.IsEqualTo senderMeetingMessageSearchBySubject = new SearchFilter.IsEqualTo(MeetingMessageSchema.Subject, senderAppointmentSubject); FindItemsResults <Item> senderMeetingRequestResult = Service.FindItems(WellKnownFolderName.Inbox, senderMeetingMessageSearchBySubject, new ItemView(1)); MeetingMessage senderMeetingMessage = senderMeetingRequestResult.First() as MeetingMessage; senderMeetingMessage.Load(); return(senderMeetingMessage); }
public FindItemsResults <Item> ObtenerEmails2(string id, string filtro, ref int total, int num, int pagina) { var extendedPropertyDefinition = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.PublicStrings, "GUID2", MapiPropertyType.String); var view = new ItemView(num, pagina * num); view.PropertySet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.InternetMessageId, EmailMessageSchema.IsRead, EmailMessageSchema.HasAttachments, EmailMessageSchema.From, EmailMessageSchema.Sender, EmailMessageSchema.Subject, EmailMessageSchema.DateTimeCreated, EmailMessageSchema.DateTimeReceived, EmailMessageSchema.DateTimeSent, EmailMessageSchema.InReplyTo, extendedPropertyDefinition); view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending); if (exchange is object) { FolderId folderId; if (string.IsNullOrEmpty(id)) { folderId = new FolderId(WellKnownFolderName.Inbox); } else { folderId = new FolderId(id); } var searchFilter = Filtrar(filtro); FindItemsResults <Item> items; if (searchFilter is object) { items = exchange.FindItems(folderId, searchFilter, view); } else { items = exchange.FindItems(folderId, view); } total = items.Count(); return(items); } else { return(null); } }
public FindItemsResults <Item> SetFolder(FindItemsResults <Item> EmailFolder, string FolderName, ExchangeService service, SearchFilter.IsEqualTo sf, string EmailAddress, string MappedMailboxAddress, Int32 ItemsAmount = 1) { FindFoldersResults Subfolders = null; if (FolderName == "inbox") { FolderId folderToAccess = new FolderId(WellKnownFolderName.Inbox, EmailAddress); if (MappedMailboxAddress != "") { folderToAccess = new FolderId(WellKnownFolderName.Inbox, MappedMailboxAddress); } if (sf != null) { EmailFolder = service.FindItems(folderToAccess, sf, new ItemView(ItemsAmount)); } else { EmailFolder = service.FindItems(folderToAccess, new ItemView(ItemsAmount)); } } else { Subfolders = service.FindFolders(WellKnownFolderName.Inbox, new FolderView(int.MaxValue)); foreach (var subfolder in Subfolders.Folders) { if (FolderName == subfolder.DisplayName.ToLower()) { if (sf != null) { EmailFolder = service.FindItems(subfolder.Id, sf, new ItemView(ItemsAmount)); } else { EmailFolder = service.FindItems(subfolder.Id, new ItemView(ItemsAmount)); } Subfolders = null; break; } } Subfolders = null; } return(EmailFolder); }
private FindItemsResults <Item> GetEmailItems() { logger.DebugFormat( "Fetching up to [{0}] email(s) from [{1}]...", numMessagesPerTick, folderId.ToString()); var findResults = exchangeService.FindItems( folderId, new ItemView(numMessagesPerTick)); logger.DebugFormat("FindItems retrieved [{0}] entries...", findResults.Count()); return(findResults); }
private void EmptyFolder(WellKnownFolderName folderName) { try { ItemView view = new ItemView(1000); view.PropertySet = new PropertySet(BasePropertySet.IdOnly); FindItemsResults <Item> findResults = _service.FindItems(folderName, view); foreach (Item i in findResults) { i.Delete(DeleteMode.HardDelete); } } catch { } }
protected static void MoveMessageToTestFolder(string subject) { EmailMessage message = null; while (message == null) { message = exchangeService.FindItems( WellKnownFolderName.Inbox, new SearchFilter.ContainsSubstring(ItemSchema.Subject, subject), new ItemView(1)).FirstOrDefault() as EmailMessage; } message.Move(testFolder.Id as FolderId); }
/// <summary> /// Create a search filter for filtering items based on whether a property exists for an item. /// </summary> /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param> private static void UseNotExistsSearchFilter(ExchangeService service) { // Create a definition for an extended property that represents a custom X-Header. ExtendedPropertyDefinition xExperimentalHeader = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.InternetHeaders, "X-Experimental", MapiPropertyType.String); // The Exists filter determines whether the a property exists on an item. // This filter indicates whether the custom X-Experimental property exists // on an item. If the Exists condition is used, then items with the // X-Experimental property are returned in the search results. The Exists // filter will return results even if the value of the property is null // or empty. SearchFilter.Exists exists = new SearchFilter.Exists(xExperimentalHeader); // The Not filter negates the result of another filter. // This filter indicates that the results of the Exists filter are negated. SearchFilter.Not not = new SearchFilter.Not(exists); // Create a nonpaged view that returns items with the Subject and X-Experimental // properties. ItemView view = new ItemView(10); view.PropertySet = new PropertySet(EmailMessageSchema.Subject, xExperimentalHeader); try { // Find items where the X-Experimental property is present on the item. This results // in a FindItem operation call to EWS. FindItemsResults <Item> results = service.FindItems(WellKnownFolderName.MsgFolderRoot, exists, view); // Process the results for finding items that contain the X-Experimental property. Console.WriteLine("Sent a request to find items where the X-Experimental property exists on the item."); UseNotExistsHelper(results, xExperimentalHeader); // Find items where the X-Experimental property is not present on the item. This results // in a FindItem operation call to EWS. FindItemsResults <Item> results2 = service.FindItems(WellKnownFolderName.MsgFolderRoot, not, view); // Process the results for finding items that do not contain the X-Experimental property. Console.WriteLine("Sent a request to find items where the X-Experimental property does not exist on the item."); UseNotExistsHelper(results2, xExperimentalHeader); } catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); } }
/// <summary> /// Create, read, update, delete message. /// </summary> /// <param name="exchangeService">Exchange service.</param> /// <returns></returns> public static async Task CreateReadUpdateDeleteMessage(ExchangeService exchangeService) { string folderName = "TestCrudItems"; await FunctionalTestHelpers.DeleteFolderIfExist( folderName, exchangeService, WellKnownFolderName.MsgFolderRoot); MailFolder mailFolder = await FunctionalTestHelpers.CreateFolder( folderName, exchangeService, WellKnownFolderName.MsgFolderRoot); for (int i = 0; i < 10; i++) { Message msg = new Message(exchangeService); msg.Subject = Guid.NewGuid().ToString(); msg.Body = new ItemBody() { ContentType = BodyType.Html, Content = $"body {Guid.NewGuid().ToString()}" }; await msg.SaveAsync(mailFolder); } FindItemResults <Message> items = await exchangeService.FindItems(mailFolder.Id, new MessageView(12)); Assert.AreEqual( 10, items.TotalCount); foreach (Message item in items) { item.Subject = $"Changed subject - {item.Subject}"; await item.UpdateAsync(); } items = await exchangeService.FindItems(mailFolder.Id, new MessageView(12)); foreach (Message item in items) { Assert.IsTrue( item.Subject.StartsWith("Changed subject -")); await item.DeleteAsync(); } }
/// <summary> /// Fecthing mails from a folder of mailbox. /// It will fetch based on subject as filter /// </summary> /// <param name="service"></param> /// <param name="FolderName"></param> /// <param name="numberOfMails"></param> /// <param name="mailboxName"></param> /// <param name="mailSubject"></param> /// <param name="isExact"></param> /// <returns></returns> static System.Collections.ObjectModel.Collection <Item> ReadMailFromFolderSubjectFilter(ExchangeService service, String FolderName, Int32 numberOfMails, String mailboxName, String mailSubject, bool isExact) { FolderView view = new FolderView(10000); view.PropertySet = new PropertySet(BasePropertySet.IdOnly); view.PropertySet.Add(FolderSchema.DisplayName); view.Traversal = FolderTraversal.Deep; Mailbox mailbox = new Mailbox(mailboxName); FindFoldersResults findFolderResults = service.FindFolders(new FolderId(WellKnownFolderName.MsgFolderRoot, mailbox), view); System.Collections.ObjectModel.Collection <Item> Items = new System.Collections.ObjectModel.Collection <Item>(); foreach (Folder folder in findFolderResults) { //For Folder filter if (folder.DisplayName == FolderName) { ItemView itemView = new ItemView(numberOfMails); if (isExact) { int counter = 0; foreach (Item item in (service.FindItems(folder.Id, itemView)).Items) { //Filtering Based on Subject if (item.Subject == (mailSubject) && counter < numberOfMails) { counter++; Items.Add(item); } } } else { int counter = 0; foreach (Item item in (service.FindItems(folder.Id, itemView)).Items) { //Filtering Based on Subject if (item.Subject.Contains(mailSubject) && counter < numberOfMails) { counter++; Items.Add(item); } } } return(Items); } } return(Items); }
//gavdcodeend 13 //gavdcodebegin 14 private static void ExportOneAppointment(ExchangeService ExService) { SearchFilter myFilter = new SearchFilter.SearchFilterCollection( LogicalOperator.And, new SearchFilter.IsEqualTo( AppointmentSchema.Subject, "This is a new meeting")); ItemView myView = new ItemView(1); FindItemsResults <Item> findResults = ExService.FindItems( WellKnownFolderName.Calendar, myFilter, myView); ItemId myAppointmentId = null; foreach (Item oneItem in findResults) { myAppointmentId = oneItem.Id; } PropertySet myPropSet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.MimeContent); Appointment appointmentToExport = Appointment.Bind(ExService, myAppointmentId, myPropSet); string apmFileName = @"C:\Temporary\myAppointment.ics"; using (FileStream myStream = new FileStream( apmFileName, FileMode.Create, FileAccess.Write)) { myStream.Write(appointmentToExport.MimeContent.Content, 0, appointmentToExport.MimeContent.Content.Length); } }
public IEnumerable <Meeting> GetMeetings(int id) { FolderId folderIdFromCalendar; try { folderIdFromCalendar = new FolderId(WellKnownFolderName.Calendar, rooms[id].Email); //Get room calendar folder } catch (Exception) { throw new System.Web.HttpException(400, "Incorrect room id"); } DateTime startDate = DateTime.Today; CalendarView cView = new CalendarView(startDate, startDate.AddDays(1), 200); //Set date FindItemsResults <Item> appointments = _service.FindItems(folderIdFromCalendar, cView); //Get Appointments by room List <Meeting> meetings = new List <Meeting>(); foreach (Appointment appointment in appointments) { meetings.Add(new Meeting() { Subject = appointment.Subject, StartTime = appointment.Start, Duration = appointment.Duration } ); } return(meetings); }
private void ReceiveEmailFromServer(ExchangeService service) { try { //创建过滤器, 条件为邮件未读. ItemView view = new ItemView(999); view.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.IsRead); SearchFilter filter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false); FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, filter, view); foreach (Item item in findResults.Items) { EmailMessage email = EmailMessage.Bind(service, item.Id); if (!email.IsRead) { LoggerHelper.Logger.Info(email.Body); //标记为已读 email.IsRead = true; //将对邮件的改动提交到服务器 email.Update(ConflictResolutionMode.AlwaysOverwrite); Object _lock = new Object(); lock (_lock) { DownLoadEmail(email.Subject, email.Body, ((System.Net.NetworkCredential)((Microsoft.Exchange.WebServices.Data.WebCredentials)service.Credentials).Credentials).UserName); } } } } catch (Exception ex) { LoggerHelper.Logger.Error(ex, "ReceiveEmailFromServer Error"); } }
static IEnumerable<Microsoft.Exchange.WebServices.Data.Task> FindIncompleteTask(ExchangeService service) { // 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, TaskSchema.Status, TaskSchema.StartDate); var filter = new SearchFilter.IsGreaterThan(TaskSchema.DateTimeCreated, DateTime.Now.AddYears(-10)); // Retrieve the items in the Tasks folder with the properties you selected. FindItemsResults<Microsoft.Exchange.WebServices.Data.Item> taskItems = service.FindItems(WellKnownFolderName.Tasks, filter, view); // If the subject of the task matches only one item, return that task item. var results = new List<Microsoft.Exchange.WebServices.Data.Task>(); foreach (var task in taskItems) { var result = new Microsoft.Exchange.WebServices.Data.Task(service); result = task as Microsoft.Exchange.WebServices.Data.Task; results.Add(result); } return results; }
//gavdcodeend 06 //gavdcodebegin 07 static void UpdateOneAppointment(ExchangeService ExService) { SearchFilter myFilter = new SearchFilter.SearchFilterCollection( LogicalOperator.And, new SearchFilter.IsEqualTo( AppointmentSchema.Subject, "This is a new meeting")); ItemView myView = new ItemView(1); FindItemsResults <Item> findResults = ExService.FindItems( WellKnownFolderName.Calendar, myFilter, myView); ItemId myAppointmentId = null; foreach (Item oneItem in findResults) { myAppointmentId = oneItem.Id; } PropertySet myPropSet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Subject, AppointmentSchema.Location); Appointment myAppointment = Appointment.Bind(ExService, myAppointmentId, myPropSet); myAppointment.Location = "Other place"; myAppointment.RequiredAttendees.Add("*****@*****.**"); myAppointment.Update(ConflictResolutionMode.AlwaysOverwrite, SendInvitationsOrCancellationsMode.SendToAllAndSaveCopy); }
private static bool DoesEmailExistInInbox(EmailMsg msg) { ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2016); service.Credentials = new WebCredentials(emailAccount, accountPassword); service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx"); SearchFilter searchFilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeSent, msg.DateTimeSent); ItemView view = new ItemView(10); var emails = service.FindItems(WellKnownFolderName.Inbox, searchFilter, view); bool found = true; foreach (var item in emails) { if (item.Subject.Equals(msg.Subject)) { found = true; item.Delete(DeleteMode.MoveToDeletedItems); break; } } return(found); }
public List <Item> GetMessages(long recordLimit) { ExchangeService service = new ExchangeService(); List <Item> messages = new List <Item>(); // Set specific credentials. service.Credentials = new NetworkCredential(UserName, Password); // Look up the user's EWS endpoint by using Autodiscover. service.AutodiscoverUrl(UserName, RedirectionCallback); // Create the item view limit based on the number of records requested from the Alteryx engine. ItemView itemView = new ItemView(recordLimit < 1 ? 1 : (recordLimit == long.MaxValue ? int.MaxValue : (int)recordLimit)); // Query items via EWS. var results = service.FindItems(Folder, QueryString, itemView); foreach (var item in results.Items) { // Bind an email message and pull the specified set of properties. Item message = Item.Bind(service, item.Id, Fields); var attachments = string.Empty; // Extract attachments from each message item if found. if (!String.IsNullOrEmpty(AttachmentPath)) { GetAttachmentsFromEmail(message); } messages.Add(message); } return(messages); }
//gavdcodeend 08 //gavdcodebegin 09 static void AcceptDeclineOneAppointment(ExchangeService ExService) { SearchFilter myFilter = new SearchFilter.SearchFilterCollection( LogicalOperator.And, new SearchFilter.IsEqualTo( AppointmentSchema.Subject, "This is a new meeting")); ItemView myView = new ItemView(1); FindItemsResults <Item> findResults = ExService.FindItems( WellKnownFolderName.Calendar, myFilter, myView); ItemId myAppointmentId = null; foreach (Item oneItem in findResults) { myAppointmentId = oneItem.Id; } PropertySet myPropSet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Subject, AppointmentSchema.Location); Appointment myAppointment = Appointment.Bind(ExService, myAppointmentId, myPropSet); myAppointment.Accept(true); //myAppointment.AcceptTentatively(true); //myAppointment.Decline(true); AcceptMeetingInvitationMessage responseMessage = myAppointment.CreateAcceptMessage(true); responseMessage.Body = new MessageBody("Meeting acknowledged"); responseMessage.Sensitivity = Sensitivity.Private; responseMessage.Send(); }
public FileAttachment GetEmail(string subject) { FindItemsResults <Item> findResults = service.FindItems( WellKnownFolderName.Inbox, new ItemView(10)); FileAttachment pdf; foreach (Item item in findResults.Items) { Console.WriteLine(item.Subject); if (item.Subject.Contains(subject)) { item.Load(); if (item.HasAttachments) { foreach (var i in item.Attachments) { // Cast i as FileAttachment type FileAttachment fileAttachment = i as FileAttachment; fileAttachment.Load(); pdf = fileAttachment; return(pdf); } } } } return(null); }
private static FindItemsResults <Item> fetchAppointments(string usr, ItemView view) { view.PropertySet = new PropertySet(ItemSchema.Subject, ItemSchema.DateTimeReceived, EmailMessageSchema.IsRead); view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending); view.Traversal = ItemTraversal.Shallow; try { // Call FindItems to find matching calendar items. // The FindItems parameters must denote the mailbox owner, // mailbox, and Calendar folder. // This method call results in a FindItem call to EWS. FindItemsResults <Item> results = service.FindItems( new FolderId(WellKnownFolderName.Calendar, usr), view); return(results); } catch (ServiceResponseException ex) { LogError("Error while fetching appointments for user '" + usr + "'"); LogErrorLine(ex.Message, ex.ErrorCode.ToString()); } catch (Exception ex) { LogError("Error while fetching appointments for user '" + usr + "'"); LogErrorLine(ex.Message); } return(null); }
public IEnumerable <EmailMessageItem> GetUnreadMessages() { LoginToExchangeService(); var searchFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false); var view = new ItemView(50) { PropertySet = new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.Subject, ItemSchema.DateTimeReceived), Traversal = ItemTraversal.Shallow }; view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending); var messages = _exchangeService.FindItems(WellKnownFolderName.Inbox, searchFilter, view).Items .OfType <EmailMessage>() .Select(n => new EmailMessageItem { MessageId = n.Id.UniqueId, Subject = n.Subject.Trim() }) .Where(n => new Regex(_settingsService.SubjectRegexFilter).IsMatch(n.Subject)) .ToList(); return(messages); }
/// <summary> /// Find email by query string /// url: https://msdn.microsoft.com/en-us/library/ee693615.aspx /// </summary> /// <param name="query">for example: "Body:Exchange"</param> /// <param name="options">options is ItemView</param> /// <returns>The Email Message</returns> public FindItemsResults <Item> Find(SearchFilter searchFilter, ItemView options = null) { if (searchFilter == null) { return(null); } if (options == null) { options = new ItemView(9); } FindItemsResults <Item> results = _exchangeService.FindItems(WellKnownFolderName.Inbox, searchFilter, options); return(results); }
/// <summary> /// Creates the contact with categories. /// </summary> /// <param name="exchangeService">The exchange service.</param> public static async Task CreateContactWithCategories(ExchangeService exchangeService) { string displayName = Guid.NewGuid().ToString(); Contact contact = new Contact(exchangeService); contact.DisplayName = displayName; contact.Department = "Dept"; contact.GivenName = "First Name"; contact.EmailAddresses.Add(new TypedEmailAddress() { Address = "*****@*****.**" }); contact.Categories = new List <string>() { "MyContactCategory" }; await contact.SaveAsync(); SearchFilter searchFilter = new SearchFilter.IsEqualTo( ContactObjectSchema.DisplayName, displayName); ContactView contactView = new ContactView(10); contactView.PropertySet.Add(ContactObjectSchema.Categories); FindItemResults <Contact> contacts = await exchangeService.FindItems <Contact>(contactView, searchFilter); Assert.AreEqual( "MyContactCategory", contacts.Items[0].Categories[0]); await contacts.Items[0].DeleteAsync(); }
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); } }
//gavdcodeend 05 //gavdcodebegin 06 static void ForwardEmail(ExchangeService ExService) { SearchFilter myFilter = new SearchFilter.SearchFilterCollection( LogicalOperator.And, new SearchFilter.IsEqualTo( EmailMessageSchema.Subject, "Email to forward")); ItemView myView = new ItemView(1); FindItemsResults <Item> findResults = ExService.FindItems( WellKnownFolderName.Inbox, myFilter, myView); ItemId myEmailId = null; foreach (Item oneItem in findResults) { myEmailId = oneItem.Id; } EmailMessage emailToReply = EmailMessage.Bind(ExService, myEmailId); EmailAddress[] forwardAddresses = new EmailAddress[1]; forwardAddresses[0] = new EmailAddress("*****@*****.**"); string myForward = "Forward body"; emailToReply.Forward(myForward, forwardAddresses); }
//gavdcodeend 04 //gavdcodebegin 05 static void FindRecurrentAppointmentsByDate(ExchangeService ExService) { SearchFilter.SearchFilterCollection myFilter = new SearchFilter.SearchFilterCollection { new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, DateTime.Now) }; ItemView myView = new ItemView(100) { PropertySet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.Duration, AppointmentSchema.AppointmentType) }; FindItemsResults <Item> foundResults = ExService.FindItems( WellKnownFolderName.Calendar, myFilter, myView); foreach (Item oneItem in foundResults.Items) { Appointment oneAppointment = oneItem as Appointment; if (oneAppointment.AppointmentType == AppointmentType.RecurringMaster) { Console.WriteLine("Subject: " + oneAppointment.Subject); Console.WriteLine("Start: " + oneAppointment.Start); Console.WriteLine("Duration: " + oneAppointment.Duration); } } }
//gavdcodeend 05 //gavdcodebegin 06 static void FindAppointmentsBySubject(ExchangeService ExService) { SearchFilter myFilter = new SearchFilter.SearchFilterCollection( LogicalOperator.And, new SearchFilter.IsEqualTo( AppointmentSchema.Subject, "This is a new meeting")); ItemView myView = new ItemView(1); FindItemsResults <Item> findResults = ExService.FindItems( WellKnownFolderName.Calendar, myFilter, myView); ItemId myAppointmentId = null; foreach (Item oneItem in findResults) { myAppointmentId = oneItem.Id; } PropertySet myPropSet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Subject, AppointmentSchema.Location); Appointment myAppointment = Appointment.Bind(ExService, myAppointmentId, myPropSet); Console.WriteLine(myAppointment.Subject + " - " + myAppointment.Location); }
public void SaveAttachment(string email, string password, string downloadfolder, string fromaddress) { ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.Credentials = new WebCredentials(email, password); service.TraceEnabled = true; service.TraceFlags = TraceFlags.All; service.AutodiscoverUrl(email, RedirectionUrlValidationCallback); // Bind the Inbox folder to the service object. Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox); // The search filter to get unread email. SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)); ItemView view = new ItemView(1); // Fire the query for the unread items. // This method call results in a FindItem call to EWS. FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view); foreach (EmailMessage item in findResults) { item.Load(); /* download attachment if any */ if (item.HasAttachments && item.Attachments[0] is FileAttachment && item.From.Address == fromaddress) { FileAttachment fileAttachment = item.Attachments[0] as FileAttachment; /* download attachment to folder */ fileAttachment.Load(downloadfolder + fileAttachment.Name); } /* mark email as read */ item.IsRead = true; item.Update(ConflictResolutionMode.AlwaysOverwrite); } }
static void Main(string[] args) { var service = new ExchangeService(); service.Credentials = new NetworkCredential("your mail address", "your password"); try { service.Url = new Uri("http://exchange01/ews/exchange.asmx"); } catch (AutodiscoverRemoteException ex) { Console.WriteLine(ex.Message); } FolderId inboxId = new FolderId(WellKnownFolderName.Inbox, "<<e-mail address>>"); var findResults = service.FindItems(inboxId, new ItemView(10)); foreach (var message in findResults.Items) { var msg = EmailMessage.Bind(service, message.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments)); foreach (Attachment attachment in msg.Attachments) { if (attachment is FileAttachment) { FileAttachment fileAttachment = attachment as FileAttachment; // Load the file attachment into memory and print out its file name. fileAttachment.Load(); var filename = fileAttachment.Name; bool b; b = filename.Contains(".csv"); if (b == true) { bool a; a = filename.Contains("meteo"); if (a == true) { var theStream = new FileStream("C:\\data\\attachments\\" + fileAttachment.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite); fileAttachment.Load(theStream); theStream.Close(); theStream.Dispose(); } } } else // Attachment is an item attachment. { // Load attachment into memory and write out the subject. ItemAttachment itemAttachment = attachment as ItemAttachment; itemAttachment.Load(); } } } }
public string actualizarRevisionDirectivaE(string asunto, string fechaInicio, string fechaLimite, string cuerpoTarea, string ubicacion) { string error = ""; try { ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010); service.UseDefaultCredentials = true; service.Credentials = new WebCredentials("xxxxxxxxxxxx", "xxxxx", "xxxx");//@uanl.mx service.AutodiscoverUrl("xxxxxxxxxxxxxxxxx"); string querystring = "Subject:'"+asunto +"'"; ItemView view = new ItemView(1); FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.Calendar, querystring, view);// <<--- Esta parte no la se pasar a VB if (results.TotalCount > 0) { if (results.Items[0] is Appointment) //if is an appointment, could be other different than appointment { Appointment appointment = results.Items[0] as Appointment; //<<--- Esta parte no la se pasar a VB if (appointment.MeetingRequestWasSent)//if was send I will update the meeting { appointment.Start = Convert.ToDateTime(fechaInicio); appointment.End = Convert.ToDateTime(fechaLimite); appointment.Body = cuerpoTarea; appointment.Location = ubicacion; appointment.Update(ConflictResolutionMode.AutoResolve); } else//if not, i will modify and sent it { appointment.Start = Convert.ToDateTime(fechaInicio); appointment.End = Convert.ToDateTime(fechaLimite); appointment.Body = cuerpoTarea; appointment.Location = ubicacion; appointment.Save(SendInvitationsMode.SendOnlyToAll); } } } else { error = "Wasn't found it's appointment"; return error; } return error; } catch { return error = "an error happend"; } }
static void Main(string[] args) { ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack; var service = new ExchangeService(ExchangeVersion.Exchange2010_SP2) { Credentials = new WebCredentials("solar_hydro_one", "Summer270"), //TraceEnabled = true, //TraceFlags = TraceFlags.All }; service.AutodiscoverUrl("*****@*****.**", RedirectionUrlValidationCallback); var rootfolder = Folder.Bind(service, WellKnownFolderName.MsgFolderRoot); rootfolder.Load(); var fid = rootfolder.FindFolders(new FolderView(3)) .Where(folder => folder.DisplayName == "Backup") .Select(folder => folder.Id).SingleOrDefault(); var dbContext = new HydroOneMeterDataContext(); var emailItems = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10)); foreach (var eItem in emailItems) { if (eItem.Subject.Contains("Hydro One Meter Data") && eItem.HasAttachments && eItem is EmailMessage) { foreach (var fileAttachment in (EmailMessage.Bind(service, eItem.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments))).Attachments.OfType<FileAttachment>().Select(attachment => attachment as FileAttachment)) { fileAttachment.Load(); Console.WriteLine("Attachment name: " + fileAttachment.Name); var hydroOneData = ProcessData(fileAttachment.Content); if (hydroOneData.Any()) { Console.WriteLine("Inserting " + hydroOneData.Count + " rows"); dbContext.HydroOneMeters.InsertAllOnSubmit(hydroOneData); } } } eItem.Move(fid); } dbContext.SubmitChanges(); Console.WriteLine("Done ... press any key to exit"); //Console.ReadKey(); }
public void accessShared() { ServicePointManager.ServerCertificateValidationCallback = m_UrlBack.CertificateValidationCallBack; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); // Get the information of the account. service.Credentials = new WebCredentials(EMAIL_ACCOUNT, EMAIL_PWD); // Set the url of server. if (!AutodiscoverUrl(service, EMAIL_ACCOUNT)) { return; } var mb = new Mailbox(SHARED_MAILBOX); var fid1 = new FolderId(WellKnownFolderName.Inbox, mb); // Add a search filter that searches on the body or subject. List<SearchFilter> searchFilterCollection = new List<SearchFilter>(); searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, SUBJECT_KEY_WORD)); SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray()); // Create a view with a page size of 10. var view = new ItemView(10); // Identify the Subject and DateTimeReceived properties to return. // Indicate that the base property will be the item identifier view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived); // Order the search results by the DateTimeReceived in descending order. view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending); // Set the traversal to shallow. (Shallow is the default option; other options are Associated and SoftDeleted.) view.Traversal = ItemTraversal.Shallow; String[] invalidStings = { "\\", ",", ":", "*", "?", "\"", "<", ">", "|" }; PropertySet itemPorpertySet = new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.MimeContent); FindItemsResults<Item> findResults = service.FindItems(fid1, searchFilter, view); foreach (Item item in findResults.Items) { EmailMessage email = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments)); email.Load(itemPorpertySet); string emailBody = email.Body.ToString(); } }
/// <summary> /// This function retuns the mail items for the given folder and for the date /// </summary> /// <param name="service"></param> /// <param name="folderId"></param> /// <param name="lastSyncDate"></param> /// <returns></returns> public FindItemsResults<Item> RetrieveMailItems(ref ExchangeService service, FolderId folderId, DateTime lastSyncDate) { //email view var emailView = new ItemView(int.MaxValue) { PropertySet = BasePropertySet.IdOnly }; //search filter collection var searchFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And) { new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, lastSyncDate) }; //retrieve var items = service.FindItems(folderId, searchFilterCollection, emailView); return items; }
public string ActualizarRevisionDirectivaCorreosE(string asunto, List<string> invitados ) { string error = ""; try { ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010); service.UseDefaultCredentials = true; service.Credentials = new WebCredentials("xxxxxxxxxxxxx", "xxxx", "xxxx"); service.AutodiscoverUrl("xxxxxxxxxxxxxxxxxxxx"); string querystring = "Subject:'" + asunto + "'"; ItemView view = new ItemView(1); FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.Calendar, querystring, view);// <<--- Esta parte no la se pasar a VB if (results.TotalCount > 0) { if (results.Items[0] is Appointment) //if is an appointment, could be other different than appointment { Appointment appointment = results.Items[0] as Appointment; //<<--- Esta parte no la se pasar a VB if (appointment.MeetingRequestWasSent)//if was send I will update the meeting { foreach (string invitado in invitados){ appointment.RequiredAttendees.Add(invitado); } appointment.Update(ConflictResolutionMode.AutoResolve); } else//if not, i will modify and sent it { appointment.Save(SendInvitationsMode.SendOnlyToAll); } } } else { error = "Wasn't found it's appointment"; return error; } return error; } catch (Exception ex) { return error = ex.Message; } }
public IEnumerable<Kontakt> GetContacts(string userName, string password) { // Exchange Online is running 2010 sp1 var service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); // passing the credentials to the service instance service.Credentials = new WebCredentials(userName, password); // AutoDiscover is done by redirection to general AutoDiscover Service, so we have to allow this service.AutodiscoverUrl(userName, delegate { return true; }); // Exchange is using an search based API, so let's look for contacts in the user's contact folder... var items = service.FindItems(WellKnownFolderName.Contacts, new ItemView(100)); return items.Cast<Contact>().Select(contact => new Kontakt { Vorname = contact.GivenName, Nachname = contact.Surname, Email = contact.EmailAddresses[EmailAddressKey.EmailAddress1].Address }); }
static void Main(string[] args) { var service = new ExchangeService(ExchangeVersion.Exchange2010); // Setting credentials is unnecessary when you connect from a computer that is logged on to the domain. service.Credentials = new WebCredentials(Settings.Default.username, Settings.Default.password, Settings.Default.domain); // Or use NetworkCredential directly (WebCredentials is a wrapper around NetworkCredential). //To set the URL manually, use the following: //service.Url = new Uri("https://proliant32.hci.tetra.ppf.cz/EWS/Exchange.asmx"); //To set the URL by using Autodiscover, use the following: service.AutodiscoverUrl("*****@*****.**"); FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10)); foreach (Item item in findResults.Items) { Console.WriteLine(item.Subject); } }
/// <summary> /// Gets e-mail using Exchange 2007. /// </summary> /// <returns></returns> public static List<OEmailLog> GetExchange2007Email() { ServicePointManager.ServerCertificateValidationCallback = TrustAllCertificates; OApplicationSetting appSetting = OApplicationSetting.Current; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.Credentials = new NetworkCredential(appSetting.EmailUserName, Security.Decrypt(appSetting.EmailPassword), appSetting.EmailDomain); service.Url = new Uri(appSetting.EmailExchangeWebServiceUrl); FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(100)); List<OEmailLog> emailList = new List<OEmailLog>(); foreach (Item item in findResults.Items) { EmailMessage emailMessage = item as EmailMessage; if (emailMessage != null) { emailMessage.Load(); OEmailLog emailLog1 = OEmailLog.WriteToEmailLog(emailMessage.From.Address, emailMessage.Subject, emailMessage.Body); //Connection.ExecuteQuery("#database", "INSERT INTO EmailLog (DateTimeReceived, FromRecipient, Subject, EmailBody, ObjectID, IsDeleted, CreatedDateTime, ModifiedDateTime, CreatedUser, ModifiedUser) VALUES ('" + DateTime.Now.ToString() + "', '" + emailMessage.From.Address + // "', '" + emailMessage.Subject + "', '" + emailMessage.Body + "', newid(), 0, getdate(), getdate(), '*** SYSTEM ***', '*** SYSTEM ***')"); //OEmailLog emailLog = TablesLogic.tEmailLog.Load(TablesLogic.tEmailLog.FromRecipient == emailMessage.From.Address & TablesLogic.tEmailLog.Subject == emailMessage.Subject); OEmailLog emailLog = TablesLogic.tEmailLog.Load(emailLog1.ObjectID); if (emailLog != null) { emailList.Add(emailLog1); emailMessage.Delete(DeleteMode.MoveToDeletedItems); } else { string message = emailMessage.From.Address + "<br/>" + emailMessage.Subject + "<br/>" + emailMessage.Body; OMessage.SendMail(appSetting.EmailForAMOSFailure, appSetting.MessageEmailSender, "Received Email Log (CAMPS CCL) Failure on " + DateTime.Now.ToString(), message, true); } } } return emailList; }
public void ConnectToExchange() { ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); ExchangeService es = new ExchangeService(ExchangeVersion.Exchange2010_SP1); es.UseDefaultCredentials = true; es.Credentials = new WebCredentials("*****@*****.**", "bulova1"); es.Url = new Uri("https://mymail.amfam.net/"); // Query the unread messages try { ItemView view = new ItemView(20); FindItemsResults<Item> findResults = es.FindItems(WellKnownFolderName.Inbox, view); foreach (EmailMessage m in findResults) { if (m.HasAttachments) { foreach (Attachment atmt in m.Attachments) { this.Eatmt = atmt; } // TODO :: Load file name into a database and Load file attachments into a directory updateEAppsTable(m.From.ToString(), m.Subject.ToString(), (DateTime)m.DateTimeReceived, (DateTime)m.DateTimeSent, this.Eatmt); } else { // TODO :: POST to database. updateEAppsTable(m.From.ToString(), m.Subject.ToString(), (DateTime)m.DateTimeReceived, (DateTime)m.DateTimeSent); } } } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }
public static FindItemsResults<Item> GetAllMessages(ExchangeService service, Folder targetFolder, int start, int length, string dateFilter, string fromFilter, string subjectFilter) { //Create empty list for all mailbox messages: var listing = new List<EmailMessage>(); //Create ItemView with correct pagesize and offset: ItemView view = new ItemView(length, start, OffsetBasePoint.Beginning); view.PropertySet = new PropertySet(EmailMessageSchema.Id, EmailMessageSchema.Subject, EmailMessageSchema.DateTimeReceived, EmailMessageSchema.From ); view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending); List<SearchFilter> searchANDFilterCollection = new List<SearchFilter>(); FindItemsResults<Item> findResults; if (!string.IsNullOrWhiteSpace(dateFilter)) { string[] dates = dateFilter.Split('~'); if (!string.IsNullOrWhiteSpace(dates[0])) { searchANDFilterCollection.Add(new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.DateTimeReceived, dates[0])); } if (!string.IsNullOrWhiteSpace(dates[1])) { searchANDFilterCollection.Add(new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeReceived, dates[1])); } } if (!string.IsNullOrWhiteSpace(fromFilter)) { searchANDFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.From, fromFilter)); } if (!string.IsNullOrWhiteSpace(subjectFilter)) { searchANDFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, subjectFilter)); } if (searchANDFilterCollection.Count > 0) { SearchFilter searchANDFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchANDFilterCollection.ToArray()); findResults = service.FindItems(targetFolder.Id, searchANDFilter, view); } else { findResults = service.FindItems(targetFolder.Id, view); } logger.Debug("FindResults Count = " + findResults.TotalCount); //bool MoreItems = true; //while(MoreItems) //{ //foreach (EmailMessage it in findResults.Items) //{ // listing.Add(it); //} //} //return View(listing.ToPagedList<EmailMessage>(pageNumber, pageSize)); return findResults; }
public static void MoveMailToDeletedFolder() { OApplicationSetting applicationSetting = OApplicationSetting.Current; ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { // trust any certificate return true; }; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.Credentials = new NetworkCredential(applicationSetting.EmailUserName, applicationSetting.EmailPassword, applicationSetting.EmailDomain); service.Url = new Uri(applicationSetting.EmailExchangeWebServiceUrl); FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10)); if (findResults.TotalCount > 0) { service.LoadPropertiesForItems(findResults.Items, PropertySet.FirstClassProperties); foreach (Item item in findResults.Items) { item.Delete(DeleteMode.MoveToDeletedItems); } } }
public static FindItemsResults<Item> GetAllMessages(ExchangeService service, Folder targetFolder, int start, int length) { //Create empty list for all mailbox messages: var listing = new List<EmailMessage>(); //Create ItemView with correct pagesize and offset: ItemView view = new ItemView(length, start, OffsetBasePoint.Beginning); view.PropertySet = new PropertySet(EmailMessageSchema.Id, EmailMessageSchema.Subject, EmailMessageSchema.DateTimeReceived, EmailMessageSchema.From ); view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending); FindItemsResults<Item> findResults = service.FindItems(targetFolder.Id, view); //bool MoreItems = true; //while(MoreItems) //{ //foreach (EmailMessage it in findResults.Items) //{ // listing.Add(it); //} //} //return View(listing.ToPagedList<EmailMessage>(pageNumber, pageSize)); return findResults; }
public static FindItemsResults<Item> GetCMessages(ExchangeService service, Folder targetFolder, string[] email, int start, int length, string datefromS, string datetoS, string toS, string fromS, string subjectS, string bodyS, string dateFilter, string fromFilter, string subjectFilter) { //Create empty list for all mailbox messages: var listing = new List<EmailMessage>(); Folder gsf = gsf = GetGlobalFolder(service); FindItemsResults<Item> findResults = null; //Create ItemView with correct pagesize and offset: ItemView view = new ItemView(length, start, OffsetBasePoint.Beginning); view.PropertySet = new PropertySet(EmailMessageSchema.Id, EmailMessageSchema.Subject, EmailMessageSchema.DateTimeReceived, EmailMessageSchema.From ); view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending); //Define the new PidTagParentDisplay property to use for filtering: ExtendedPropertyDefinition def = new ExtendedPropertyDefinition(0x0E05, MapiPropertyType.String); List<SearchFilter> searchANDFilterCollection = new List<SearchFilter>(); List<SearchFilter> searchORcommCollection = new List<SearchFilter>(); List<SearchFilter> searchCompCollection = new List<SearchFilter>(); //Add "OR" commissioner search criteria: if (email != null && email.Count() > 0) { foreach (var target in email) { string t = target; if (target.Contains('@')) { t = target.Split('@')[0]; } searchORcommCollection.Add(new SearchFilter.ContainsSubstring(def, t.ToLower())); logger.Debug("Added mailbox to searchOR collection: " + target); } } if (searchORcommCollection.Count > 0) { SearchFilter searchOrFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchORcommCollection.ToArray()); searchCompCollection.Add(searchOrFilter); } //Populate fields from the SEARCH form (not the filters, just the search): if (!string.IsNullOrWhiteSpace(datefromS)) { DateTime dFrom = DateTime.Parse(datefromS + " 12:00AM"); logger.Debug("datefromS -- " + dFrom.ToString()); searchANDFilterCollection.Add(new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.DateTimeReceived, dFrom)); } if (!string.IsNullOrWhiteSpace(datetoS)) { DateTime dTo = DateTime.Parse(datetoS + " 11:59PM"); logger.Debug("datetoS -- " + dTo.ToString()); searchANDFilterCollection.Add(new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeReceived, dTo)); } if (!string.IsNullOrWhiteSpace(fromS)) { searchANDFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.From, fromS)); } if (!string.IsNullOrWhiteSpace(toS)) { searchANDFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.DisplayTo, toS)); } if (!string.IsNullOrWhiteSpace(subjectS)) { searchANDFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, subjectS)); } if (!string.IsNullOrWhiteSpace(bodyS)) { searchANDFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.Body, bodyS)); } //Populate fields from Datatables FILTER form (this supplements the SEARCH form): if (!string.IsNullOrWhiteSpace(dateFilter)) { string[] dates = dateFilter.Split('~'); if (!string.IsNullOrWhiteSpace(dates[0])) { DateTime dfFrom = DateTime.Parse(dates[0] + " 12:00AM"); logger.Debug("dfFrom -- " + dfFrom.ToString()); searchANDFilterCollection.Add(new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.DateTimeReceived, dfFrom)); } if (!string.IsNullOrWhiteSpace(dates[1])) { DateTime dfTo = DateTime.Parse(dates[1] + " 11:59PM"); logger.Debug("dfTo -- " + dfTo.ToString()); searchANDFilterCollection.Add(new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeReceived, dfTo)); } } if (!string.IsNullOrWhiteSpace(fromFilter)) { searchANDFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.From, fromFilter)); } if (!string.IsNullOrWhiteSpace(subjectFilter)) { searchANDFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, subjectFilter)); } //Assemble the SearchFilter Collection if (searchANDFilterCollection.Count > 0) { SearchFilter searchANDFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchANDFilterCollection.ToArray()); searchCompCollection.Add(searchANDFilter); } //Evaluate filters and execute find results: if (searchORcommCollection.Count > 0 || searchANDFilterCollection.Count > 0) { SearchFilter searchComp = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchCompCollection.ToArray()); findResults = service.FindItems(targetFolder.Id, searchComp, view); } else { findResults = service.FindItems(targetFolder.Id, view); } logger.Debug("FindResults Count = " + findResults.TotalCount); return findResults; }
private List<Item> GetItems(ExchangeService service, SearchFilter filter, WellKnownFolderName folder, PropertySet propertySet) { if (service == null) { return null; } List<Item> items = new List<Item>(); if (propertySet == null) { propertySet = new PropertySet(BasePropertySet.IdOnly); } const Int32 pageSize = 50; ItemView itemView = new ItemView(pageSize); itemView.PropertySet = propertySet; FindItemsResults<Item> searchResults = null; try { do { searchResults = service.FindItems(folder, filter, itemView); items.AddRange(searchResults.Items); itemView.Offset += pageSize; } while (searchResults.MoreAvailable); } catch (Exception ex) { NotifyDownloadStatus(DownloadStatus.INFORM, ex.Message); return null; } return items; }
static void Main(string[] args) { /*DateTime dateResult; CultureInfo culture; culture = CultureInfo.CreateSpecificCulture("en-US"); DateTimeStyles styles; styles = DateTimeStyles.None; DateTime.TryParseExact("16/07/2013", "dd/MM/yyyy", culture, styles, out dateResult);*/ /*string dateString; CultureInfo culture; DateTimeStyles styles; culture = CultureInfo.CreateSpecificCulture("en-UK"); DateTime dateResult; // Parse a date and time with no styles. dateString = "17/01/2009 10:00 AM"; styles = DateTimeStyles.None; if (DateTime.TryParse(dateString, culture, styles, out dateResult)) { ; }*/ /*string[] banklist1 = { "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**" }; foreach (string bank in banklist1) { Console.WriteLine("Start to update " + bank); updateExcel(@"D:\2013-6-24", bank.ToLower(), @"D:\SFTP\Fund position.xlsx"); }*/ //OpearateCSV.temp(); //FindFileForPimCO(@"D:\2013-6-24\", @"D:\Projects\Fund position.xlsx"); //FindFileForCiti(@"D:\2013-4-1\AM", @"\\ssgfs01\Dept_SG\Finance\Treasury\Treasury Limited Access\Fund Position\Automation\Apr 13\Fund position-1 Apr 2013_AM.xlsx"); //FindFileForHSBC(@"D:\2013-7-16\AM", @"\\ssgfs01\Dept_SG\Finance\Treasury\Treasury Limited Access\Fund Position\Automation\Jul 13\Fund position-16 Jul 2013_AM.xlsx"); //FindFileForJPM(@"D:\2011-12-9\Asia Liquidity Client Services JPMAM", @"\\ssgfs01\Dept_SG\Finance\Treasury\Treasury Limited Access\Fund Position\Automation\Jan 12\Fund position-17 Jan 2012.xlsx"); //Console.WriteLine(DateTime.Now.ToShortDateString()); string updatefolderpath = @"\\ssgfs01\Dept_SG\Finance\Treasury\Treasury Limited Access\Fund Position\Automation\"+strMonth(DateTime.Now.Month)+DateTime.Now.Year.ToString().Substring(2,2); if (!Directory.Exists(updatefolderpath)) { System.IO.Directory.CreateDirectory(updatefolderpath); } string originalfilename = @"\\ssgfs01\Dept_SG\Finance\Treasury\Treasury Limited Access\Fund Position\Automation\Fund position.xlsx"; FileInfo fi = new FileInfo(originalfilename); string updatefilename=updatefolderpath + @"\Fund position-" + DateTime.Now.Day + " " + strMonth(DateTime.Now.Month) + " " + DateTime.Now.Year+"_AM.xlsx"; fi.CopyTo(updatefilename, true); //FindFileForGS(@"D:\2011-12-23\Service Center, GSAM Institutional", updatefilename); //UnZipHSBCZIP(@"D:\2011-12-12\[email protected]"); //FindFileForGS(@"D:\2011-12-12\Service Center, GSAM Institutional"); //FindFileForJPM(@"D:\Copy of 2011-12-9\Asia Liquidity Client Services JPMAM"); //FindFileForSCB(@"D:\2011-12-2\Standard Chartered Bank\10703008"); //SharpZip.UnZipFileForAES(@"D:\2011-11-29\REGISTEREXTRACT 111123.zip", "*****@*****.**"); //FindFileForSCB("D:\\2011-11-29\\Standard Chartered Bank"); //SharpZip.UnZipFileForAES(@"D:\2011-11-29\10620467.zip", "Standard Chartered Bank"); //string userName="******"; //string userName = WindowsIdentity.GetCurrent().Name; //string password="******"; //string Domain="asiacapitalre"; bool ishsbc = false; string hsbcfoldername = string.Empty; ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { // trust any certificate return true; }; string folderpath = "d:\\" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day+"\\AM"; if (!Directory.Exists(folderpath)) { System.IO.Directory.CreateDirectory(folderpath); } ExchangeService service = new ExchangeService(); //NetworkCredential nc = new NetworkCredential(userName, password, "asiacapitalre"); NetworkCredential nc = CredentialCache.DefaultNetworkCredentials; service.Credentials = nc; ; service.Url = new Uri("https://webmail.asiacapitalre.com/EWS/Exchange.asmx"); var result=service.FindItems(WellKnownFolderName.Inbox,new ItemView(100)).Reverse(); string filename = string.Empty; string bankname = string.Empty; Console.WriteLine("Start to Read Mail"); Folder rootfolder = Folder.Bind(service, WellKnownFolderName.MsgFolderRoot); List<string> banklist = new List<string>(); string accountforzero = string.Empty; foreach (var e in result) { EmailMessage em = EmailMessage.Bind(service, new ItemId(e.Id.UniqueId), new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, EmailMessageSchema.From,EmailMessageSchema.Subject)); AttachmentCollection ac = em.Attachments; bankname = em.From.Address; if (bankname.ToLower().IndexOf("@hsbc") != -1) { ishsbc = true; hsbcfoldername = bankname; accountforzero += "HSBC Singapore,HSBC MYR,HSBC HK,HSBC Japan Rep,HSBC HK Branch,HSBC India Rep,HSBC Taiwan Rep,"; } if (bankname.ToLower().IndexOf("@citi") != -1) { accountforzero += "Citibank Singapore,Citi Bonds (USD),Citi Bonds (LCY),Citi Equities (USD),Citi Equities (LCY),Citibank HK Branch,Citi Bonds HK Branch,"; } if (bankname.ToLower().IndexOf("@jpm") != -1) { accountforzero += "JPM,"; } if (bankname.ToLower().IndexOf("bnpparibas.com") != -1) { accountforzero += "RMB fund-ACRG,RMB fund-ACRG HK branch,"; } if (bankname.ToLower().IndexOf("standardchartered.com") != -1) { accountforzero += "Std Chartered,"; } if (bankname.ToLower().IndexOf("bbh.com") != -1) { accountforzero += "Total Return Bond Fund,"; } if (bankname.ToLower().IndexOf("gs.com") != -1) { accountforzero += "GS,"; } if(!banklist.Contains(bankname)) banklist.Add(bankname); if (!Directory.Exists(folderpath+"\\"+bankname)) { System.IO.Directory.CreateDirectory(folderpath + "\\" + bankname); } foreach (Attachment at in ac) { FileAttachment fa = at as FileAttachment; filename = folderpath + "\\" + bankname + "\\" + at.Name; Console.WriteLine("Start to download attachment"+at.Name); fa.Load(filename); if (Path.GetExtension(filename) == ".zip") { Console.WriteLine("Start to upzip attachment" + at.Name); SharpZip.UnZipFileForAES(filename, bankname); } } Item item = Item.Bind(service, e.Id.UniqueId); Folder folder = rootfolder.FindFolders(new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Backup"), new FolderView(1)).First(); Console.WriteLine("Start to move " + em.Subject); item.Move(folder.Id); } //If HSBC has mail, start to dowload FTP //string HSBCPath = folderpath + "\\" + "*****@*****.**"; string HSBCPath = folderpath + "\\" + hsbcfoldername; if (ishsbc) { Console.WriteLine("Start to download HSBCFTP"); DownloadFTP.DownloadSFTP(HSBCPath + "\\"); Console.WriteLine("Start to upzip HSBCattachment"); UnZipHSBCZIP(HSBCPath); } if (accountforzero.Length > 0) //Check if there is account to be N/A OpearateCSV.CheckAccount(updatefilename, accountforzero.Substring(0, accountforzero.Length - 1).Split(',')); else { Console.WriteLine("No need to update excel"); return; } Console.WriteLine("Start to update excel"); foreach (string bank in banklist) { Console.WriteLine("Start to update "+bank); updateExcel(folderpath,bank.ToLower(),updatefilename); } Console.WriteLine("Start to overwirte the original excel"); FileInfo fi2 = new FileInfo(updatefilename); fi2.CopyTo(originalfilename, true); //Console.ReadLine(); }
private List<MailItem> SearchSubFolders(ExchangeService service, WellKnownFolderName parentFolder, MailSearchContainerNameList subFolderNames, string mailBoxName, SearchFilter.SearchFilterCollection searchFilters) { var result = new List<MailItem>(); try { var subFolders = FindSubFolders(service, parentFolder, subFolderNames); if (subFolders == null || subFolders.Count() <= 0) return result; var itemView = new ItemView(VIEW_SIZE); itemView.PropertySet = new PropertySet {ItemSchema.Id, ItemSchema.HasAttachments, ItemSchema.Subject, ItemSchema.Body}; foreach (var subFolder in subFolders) { var matches = service.FindItems(subFolder.Id, searchFilters, itemView); AddItems(service, matches, result,mailBoxName,subFolder.DisplayName); } } catch (Exception ex) { //Ignore Debug.WriteLine(string.Format("Error encountered searching subfolders: {0}\n {1}", ex.ToString(), ex.StackTrace.ToString())); } return result; }
protected void loadData(string keyword) { int clientID = Core.SessionHelper.getClientId(); IQueryable<CRM.Data.Entities.Contact> contacts = null; if (keyword == null) { contacts = ContactManager.GetAll(clientID); } else { contacts = ContactManager.Search(keyword, clientID); } List<CRM.Data.Entities.Contact> contactList = contacts.ToList(); int userID = SessionHelper.getUserId(); CRM.Data.Entities.SecUser secUser = SecUserManager.GetByUserId(userID); string email = secUser.Email; string password = SecurityManager.Decrypt(secUser.emailPassword); string url = "https://" + secUser.emailHost + "/EWS/Exchange.asmx"; try { ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.Credentials = new WebCredentials(email, password); service.Url = new Uri(url); ContactsFolder contactsfolder = ContactsFolder.Bind(service, WellKnownFolderName.Contacts); int numItems = contactsfolder.TotalCount < 50 ? contactsfolder.TotalCount : 50; ItemView view = new ItemView(int.MaxValue); view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName); FindItemsResults<Item> contactItems = service.FindItems(WellKnownFolderName.Contacts, view); foreach (Item item in contactItems) { if (item is Microsoft.Exchange.WebServices.Data.Contact) { item.Load(); Microsoft.Exchange.WebServices.Data.Contact contact = item as Microsoft.Exchange.WebServices.Data.Contact; CRM.Data.Entities.Contact newContact = new Data.Entities.Contact(); newContact.FirstName = contact.GivenName; newContact.LastName = contact.Surname; newContact.Email = contact.EmailAddresses[0].Address; newContact.DepartmentName = "Outlook"; bool exist = false; if (keyword == null || keyword[0] == newContact.Email[0]) foreach (var con in contactList) { if (con.Email == newContact.Email) exist = true; } if (!exist) contactList.Add(newContact); } } } catch (Exception ex) { } gvContact.DataSource = contactList; gvContact.DataBind(); }
private List<X> GetMailIdsToProcess(ExchangeService service, FolderId inboxFolder) { var propertySet = new PropertySet( BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived); propertySet.RequestedBodyType = BodyType.Text; var view = new ItemView(50); view.PropertySet = propertySet; var searchFilters = new List<SearchFilter>() { new SearchFilter.IsGreaterThan(ItemSchema.DateTimeReceived, DateTime.Today) }; var searchFilter = new SearchFilter.SearchFilterCollection( LogicalOperator.And, searchFilters.ToArray()); view.Traversal = ItemTraversal.Shallow; var mailIds = new List<X>(); var mailsToday = service.FindItems(inboxFolder, searchFilter, view); if (mailsToday.Count() > 0) { mailIds.AddRange(mailsToday.Select(mt => new X() { ItemId = mt.Id.UniqueId, Subject = mt.Subject })); } while (mailsToday.MoreAvailable) { mailsToday = service.FindItems(inboxFolder, searchFilter, view); if (mailsToday.Count() > 0) { mailIds.AddRange(mailsToday.Select(mt => new X() { ItemId = mt.Id.UniqueId, Subject = mt.Subject })); } } return mailIds; }
public static FindItemsResults<Item> GetItems(ExchangeService service, string address) { var searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)); //var searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.Subject, "MyExchangeTest")); var mailbox = new Mailbox(address); var folderId = new FolderId(WellKnownFolderName.Inbox, mailbox); var items = service.FindItems(folderId, searchFilter, new ItemView(5)); return items; }
private void OnStartAfter() { string sMailBox = System.String.Empty; string sMailServerUrl = System.String.Empty; string sUser = System.String.Empty; string sPassword = System.String.Empty; string sDomain = System.String.Empty; string sFolderRoot = System.String.Empty; int iItemsProccesing = 0; int iScanDelay = 0; Boolean bFolderDestDomain = false; Boolean bDestinationFileFormatLong = false; Boolean bProcessingFileToLog = false; if (!EventLog.SourceExists(sSource)) EventLog.CreateEventSource(sSource, sLog); sEvent = "Service started"; EventLog.WriteEntry(sSource, sEvent); try { sMailBox = ConfigurationManager.AppSettings["MailBox"]; sMailServerUrl = ConfigurationManager.AppSettings["MailServerUrl"]; sUser = ConfigurationManager.AppSettings["User"]; sPassword = ConfigurationManager.AppSettings["Password"]; sDomain = ConfigurationManager.AppSettings["Domain"]; sFolderRoot = ConfigurationManager.AppSettings["FolderRoot"]; iItemsProccesing = Convert.ToInt32(ConfigurationManager.AppSettings["ItemsProccesing"]); // How much emails retrieve to view iScanDelay = Convert.ToInt32(ConfigurationManager.AppSettings["ScanDelay"]); // Delay between scan Inbox bFolderDestDomain = Convert.ToBoolean(ConfigurationManager.AppSettings["FolderDestinationNameWithDomain"]); bDestinationFileFormatLong = Convert.ToBoolean(ConfigurationManager.AppSettings["DestinationFileFormatLong"]); // bProcessingFileToLog = Convert.ToBoolean(ConfigurationManager.AppSettings["ProcessingFileToLog"]); // sEvent = "MailBox=" + sMailBox + "\n" + "MailServerUrl=" + sMailServerUrl + "\n" + "User="******"\n" + "Domain=" + sDomain + "\n" + "FolderRoot=" + sFolderRoot + "\n" + "ItemsProccesing=" + iItemsProccesing + "\n" + "ScanDelay=" + iScanDelay + "\n" + "FolderDestDomain=" + bFolderDestDomain + "\n" + "DestinationFileFormatLong=" + bDestinationFileFormatLong + "\n" + "ProcessingFileToLog=" + bProcessingFileToLog; EventLog.WriteEntry(sSource, sEvent); } catch (Exception e) { EventLog.WriteEntry(sSource, e.Message, EventLogEntryType.Warning, 234); } ////////////////////; // Boolean bItemDelete = false; string sFilePath = System.String.Empty; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); ServicePointManager.ServerCertificateValidationCallback = (obj, certificate, chain, errors) => true; service.Credentials = new System.Net.NetworkCredential(sUser, sPassword, sDomain); Uri uriMailServerUrl = new Uri(sMailServerUrl); service.Url = uriMailServerUrl; FolderId InboxId = new FolderId(WellKnownFolderName.Inbox, sMailBox); FindItemsResults<Item> findResults = null; while (true) { try { findResults = service.FindItems(InboxId, new ItemView(iItemsProccesing)); } catch (Exception e) { sEvent = "Exchange Server:" +e.Source + ":" + e.Message; EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning, 234); } if (findResults != null) { foreach (Item message in findResults.Items) { bItemDelete = true; if (message.HasAttachments) { EmailMessage emailMessage = EmailMessage.Bind(service, message.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments)); #if DEBUG sEvent = "Debug event Subject: " + message.Subject + " Date: " + message.DateTimeReceived; EventLog.WriteEntry(sSource, sEvent ); #endif emailMessage.Load(); string sSenderAdddress = emailMessage.From.Address; String sFolderPath = GetPath(bFolderDestDomain, message.DateTimeReceived, sFolderRoot, sSenderAdddress); foreach (Attachment attachment in emailMessage.Attachments) { FileAttachment fileAttachment = attachment as FileAttachment; if (bDestinationFileFormatLong) { string sNewFileName = AttachFileName(fileAttachment.Name, message.DateTimeReceived); sFilePath = sFolderPath + sNewFileName; } else { sFilePath = sFolderPath + fileAttachment.Name; } if (bProcessingFileToLog) { sEvent = "File stored path=" + sFilePath; EventLog.WriteEntry(sSource, sEvent); } try { fileAttachment.Load(sFilePath); } catch (System.UnauthorizedAccessException e) { sEvent = e.Source + ":" + e.Message; EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning, 234); bItemDelete = false; } catch (Exception e) { sEvent = e.Source + ":" + e.Message; EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning, 234); bItemDelete = false; } } } // Move processed item to \Deleted items if (bItemDelete) message.Delete(DeleteMode.MoveToDeletedItems); } } System.Threading.Thread.Sleep(iScanDelay); } }
private List<Item> GetItems(ExchangeService service, SearchFilter filter, WellKnownFolderName folder, PropertySet propertySet) { if (service == null) { return null; } List<Item> items = new List<Item>(); if (propertySet == null) { propertySet = new PropertySet(BasePropertySet.IdOnly); } const Int32 pageSize = 50; ItemView itemView = new ItemView(pageSize); itemView.PropertySet = propertySet; FindItemsResults<Item> searchResults = null; try { do { searchResults = service.FindItems(folder, filter, itemView); items.AddRange(searchResults.Items); itemView.Offset += pageSize; } while (searchResults.MoreAvailable); } catch (Exception ex) { if (!CheckServerConnection(domain)) { NotifyDownloadStatus(DownloadStatus.INFORM, CMController.Properties.Resources.unconnect_exchange_server); return null; } else { NotifyDownloadStatus(DownloadStatus.INFORM, CMController.Properties.Resources.wrong_username_password); return null; } } return items; }
protected void Page_Load(object sender, EventArgs e) { // access master page from nested master page Protected.ClaimRuler masterPage = Master.Master as Protected.ClaimRuler; // check user permission //masterPage.checkPermission(); clientID = SessionHelper.getClientId(); // get current lead leadID = SessionHelper.getLeadId(); // get current lead id claimID = SessionHelper.getClaimID(); // get current user userID = SessionHelper.getUserId(); // set directory where client can upload pictures for signature txtSignature.UploadedFilesDirectory = appPath + "/clientLogo/" + clientID; if (!Page.IsPostBack) { bindData(); userID = SessionHelper.getUserId(); CRM.Data.Entities.SecUser secUser = SecUserManager.GetByUserId(userID); string email = secUser.Email; string password =SecurityManager.Decrypt(secUser.emailPassword); string url = "https://" + secUser.emailHost + "/EWS/Exchange.asmx"; try { ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.Credentials = new WebCredentials(email, password); service.Url = new Uri(url); ContactsFolder contactsfolder = ContactsFolder.Bind(service, WellKnownFolderName.Contacts); int numItems = contactsfolder.TotalCount < 50 ? contactsfolder.TotalCount : 50; ItemView view = new ItemView(int.MaxValue); view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName); FindItemsResults<Item> contactItems = service.FindItems(WellKnownFolderName.Contacts, view); DataTable table = new DataTable(); table.Columns.Add("FirstName", typeof(string)); table.Columns.Add("LastName", typeof(string)); table.Columns.Add("CompanyName", typeof(string)); table.Columns.Add("Email", typeof(string)); table.Columns.Add("ContactType", typeof(string)); foreach (GridRecord crow in contractGrid.Rows) { DataRow row = table.NewRow(); row[0] = crow.Items[0].Text; row[1] = crow.Items[1].Text; //row[2] = crow.Cells[2].Text; row[3] = crow.Items[3].Text; row[4] = crow.Items[4].Text; table.Rows.Add(row); } foreach (Item item in contactItems) { if (item is Microsoft.Exchange.WebServices.Data.Contact) { item.Load(); Microsoft.Exchange.WebServices.Data.Contact contact = item as Microsoft.Exchange.WebServices.Data.Contact; DataRow row = table.NewRow(); row[0] = contact.GivenName; row[1] =contact.Surname; row[3] =contact.EmailAddresses[0].Address; row[4] ="Outlook"; table.Rows.Add(row); } } contractGrid.DataSourceID = null; contractGrid.Columns.Clear(); contractGrid.DataBind(); contractGrid.DataSource = table; contractGrid.DataBind(); } catch (Exception ex) { } } }
private void bindTasks(DateTime fromDate, DateTime toDate) { List<LeadTask> tasks = null; Expression<Func<CRM.Data.Entities.Task, bool>> predicate = PredicateBuilder.True<CRM.Data.Entities.Task>(); if (roleID == (int)UserRole.Administrator) { } else if ((roleID == (int)UserRole.Client || roleID == (int)UserRole.SiteAdministrator) && clientID > 0) { // load all tasks for client (sort of admin) predicate = predicate.And(LeadTask => LeadTask.creator_id == clientID); predicate = predicate.And(LeadTask => LeadTask.start_date >= fromDate && LeadTask.end_date <= toDate); // get overdue task for client predicate = predicate.Or(LeadTask => LeadTask.status_id == 1 && LeadTask.end_date <= toDate && LeadTask.creator_id == clientID); } else { // regular users predicate = predicate.And(LeadTask => LeadTask.start_date >= fromDate && LeadTask.end_date <= toDate); predicate = predicate.And(LeadTask => LeadTask.owner_id == userID); } tasks = TasksManager.GetLeadTask(predicate, fromDate, toDate); if (rbOn.Checked) { userID = SessionHelper.getUserId(); CRM.Data.Entities.SecUser secUser = SecUserManager.GetByUserId(userID); string emailaddress = secUser.Email; string password = SecurityManager.Decrypt(secUser.emailPassword); string url = "https://" + secUser.emailHost + "/EWS/Exchange.asmx"; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.Credentials = new WebCredentials(emailaddress, password); service.Url = new Uri(url); try { TasksFolder tasksfolder = TasksFolder.Bind(service, WellKnownFolderName.Tasks); ItemView view = new ItemView(int.MaxValue); FindItemsResults<Item> OutlookTasks = tasksfolder.FindItems(view); CalendarView calView = new CalendarView(fromDate, toDate); FindItemsResults<Item> instanceResults = service.FindItems(WellKnownFolderName.Calendar, calView); foreach (var item in instanceResults) { LeadTask newTask = new LeadTask(); Microsoft.Exchange.WebServices.Data.Appointment appointment = item as Microsoft.Exchange.WebServices.Data.Appointment; newTask.creator_id = userID; newTask.details = appointment.Subject; newTask.end_date = appointment.End; newTask.isAllDay = appointment.IsRecurring; newTask.text = appointment.Subject; newTask.priorityName = appointment.Importance.ToString(); newTask.owner_name = appointment.Organizer.Name; newTask.start_date = appointment.Start; tasks.Add(newTask); } foreach (var task in OutlookTasks) { task.Load(); Microsoft.Exchange.WebServices.Data.Task myTask = task as Microsoft.Exchange.WebServices.Data.Task; LeadTask newTask = new LeadTask(); newTask.creator_id = userID; newTask.details = ExtractHtmlInnerText(myTask.Body.Text); newTask.end_date = myTask.DueDate; newTask.isAllDay = myTask.IsRecurring; newTask.text = myTask.Subject; newTask.statusName = myTask.Status.ToString(); newTask.priorityName = myTask.Importance.ToString(); newTask.owner_name = myTask.Owner; if (myTask.StartDate == null) newTask.start_date = myTask.DueDate; else newTask.start_date = myTask.StartDate; tasks.Add(newTask); } } catch (Exception ex) { } } // show tasks gvTasks.DataSource = tasks; gvTasks.DataBind(); }
private List<MailItem> SearchSharedMailBoxes(ExchangeService service, ItemView view, SearchFilter.SearchFilterCollection searchFilters, MailSearchContainerNameList mailBoxNames, string mailDomain, string searchTerm) { var result = new List<MailItem>(); if (mailBoxNames == null || mailBoxNames.Count <= 0 ) return result; foreach (var mailBoxName in mailBoxNames) { try { var fullyQualifiedMailboxName = String.Format("{0}@{1}", mailBoxName, mailDomain); Mailbox mb = new Mailbox(fullyQualifiedMailboxName); FolderId fid1 = new FolderId(WellKnownFolderName.Inbox, mb); var rootFolder = Folder.Bind(service, fid1); var items = rootFolder.FindItems(view); service.LoadPropertiesForItems(items, new PropertySet { ItemSchema.Attachments, ItemSchema.HasAttachments }); var matches = service.FindItems(fid1, searchFilters, view); AddItems(service, matches, result, fullyQualifiedMailboxName, "InBox"); } catch (ServiceResponseException) { //Ignore this indicates the user has no access to the mail box. Debug.WriteLine(String.Format("Trouble accessing mailbox {0} assuming no access.", mailBoxName)); } } return result; }
private static void getMail() { ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010); service.Credentials = new System.Net.NetworkCredential( "neville.kuyt", "0bvious!", "EMEA" ); service.AutodiscoverUrl("*****@*****.**"); log.Debug("Connecting to email server" + service.ServerInfo); FindItemsResults<Item> findTravelResults = service.FindItems(WellKnownFolderName.Inbox, "System.Message.FromAddress:=*@chamberstravel.com AND System.Subject:Ticketed itinerary for*", new ItemView(10)); service.LoadPropertiesForItems(findTravelResults, PropertySet.FirstClassProperties); log.Debug("Found " + findTravelResults.Items.Count + " mails"); foreach (Item item in findTravelResults.Items) { log.Debug(item.Subject); parseMail(item); } }
/// <summary> /// This function gets the mail item by the extended property /// </summary> /// <param name="service"></param> /// <param name="folderId"></param> /// <param name="msgFolderRootId"></param> /// <param name="outlookMsgId"></param> /// <param name="isIn"></param> /// <returns></returns> public object GetMailItemByExtendedProperty(ref ExchangeService service, FolderId folderId, FolderId msgFolderRootId, string outlookMsgId, bool isIn) { EmailMessage message = null; //Folder view var viewFolders = new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep, PropertySet = new PropertySet(BasePropertySet.IdOnly) }; //email view var viewEmails = new ItemView(int.MaxValue) { PropertySet = new PropertySet(BasePropertySet.IdOnly) }; //email filter SearchFilter emailFilter = new SearchFilter.IsEqualTo( isIn ? MailboxExtendedPropertyDefinitionInbox : MailboxExtendedPropertyDefinitionSent, outlookMsgId); //search item in default folder var findResults = service.FindItems(msgFolderRootId, emailFilter, viewEmails); //check if ((findResults != null) && findResults.TotalCount > 0 && findResults.FirstOrDefault() is EmailMessage) { //we found the email in default folder message = (EmailMessage)findResults.First(); } else { //find in all folders var allFolders = service.FindFolders(msgFolderRootId, viewFolders); foreach (var folder in allFolders.Folders) { //search findResults = service.FindItems(folder.Id, emailFilter, viewEmails); //check if ((findResults != null) && findResults.TotalCount > 0 && findResults.FirstOrDefault() is EmailMessage) { //we found the email in somewhere message = (EmailMessage)findResults.First(); break; } } } if (message != null) { //create property set and load necessary properties var propertySet = new PropertySet(EmailMessageSchema.ToRecipients, EmailMessageSchema.Sender, ItemSchema.Subject, ItemSchema.Body, ItemSchema.DateTimeReceived, ItemSchema.DateTimeSent, ItemSchema.HasAttachments, ItemSchema.Attachments) { RequestedBodyType = BodyType.HTML }; //load properties service.LoadPropertiesForItems(findResults, propertySet); } return message; }
public static List<EmailMessage> GetAllEmails(ExchangeService service) { int offset = 0; int pageSize = 50; bool more = true; ItemView view = new ItemView(pageSize, offset, OffsetBasePoint.Beginning); view.PropertySet = PropertySet.IdOnly; FindItemsResults<Item> findResults; List<EmailMessage> emails = new List<EmailMessage>(); while (more) { findResults = service.FindItems(WellKnownFolderName.Inbox, view); foreach (var item in findResults.Items) { emails.Add((EmailMessage)item); } more = findResults.MoreAvailable; if (more) { view.Offset += pageSize; } } PropertySet properties = (BasePropertySet.FirstClassProperties); //A PropertySet with the explicit properties you want goes here service.LoadPropertiesForItems(emails, properties); return emails; }
private List<Item> GetItems(ExchangeService service, SearchFilter filter, WellKnownFolderName folder, PropertySet propertySet) { if (service == null) { return null; } List<Item> items = new List<Item>(); if (propertySet == null) { propertySet = new PropertySet(BasePropertySet.IdOnly); } const Int32 pageSize = 50; ItemView itemView = new ItemView(pageSize); itemView.PropertySet = propertySet; FindItemsResults<Item> searchResults = null; try { do { searchResults = service.FindItems(folder, filter, itemView); items.AddRange(searchResults.Items); itemView.Offset += pageSize; } while (searchResults.MoreAvailable); } catch (Exception ex) { if (!CheckServerConnection(domain)) { NotifyDownloadStatus(DownloadStatus.INFORM, "Unable to connect to Exchange server. Please check."); } else { NotifyDownloadStatus(DownloadStatus.INFORM, "The username or password is incorrect. Please try again."); } return null; } return items; }