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; } }
static void Main(string[] args) { ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2016); service.Url = new Uri("https://172.25.10.12/EWS/Exchange.asmx"); service.Credentials = new WebCredentials("*****@*****.**", "Qwerty1234"); service.TraceEnabled = false; var rooms = GetAllRooms(); var meetings = GetAllMeetings(rooms, service, new TimeWindow(DateTime.Now.AddMinutes(-30), DateTime.Now)); //var a = meetings[0].Delete(DeleteMode.MoveToDeletedItems, SendCancellationsMode.SendToAllAndSaveCopy).Result; var org = service.ResolveName(meetings[0].Organizer.Name).Result; service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, org.FirstOrDefault().Mailbox.Address); var calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet()).Result; CalendarView cView = new CalendarView(DateTime.Now.AddMinutes(-30), DateTime.Now, 100); // Limit the properties returned to the appointment's subject, start time, and end time. //cView.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End); // Retrieve a collection of appointments by using the calendar view. FindItemsResults <Appointment> appointments = calendar.FindAppointments(cView).Result; //appointments.FirstOrDefault(x=>x.id) var res = appointments.Items[0].CancelMeeting("No one shoved up").Result; Console.ReadLine(); }
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 static List <CalendarItem> ReadTodaysCalendarItems() { ItemView view = new ItemView(10); DateTime Start = DateTime.Now; DateTime End = DateTime.Today.AddDays(2); CalendarView calView = new CalendarView(Start, End); List <CalendarItem> CalendarItems = new List <CalendarItem>(); FindItemsResults <Item> SearchResults = CreateExchangeConnection().FindItems(WellKnownFolderName.Calendar, calView); foreach (Item item in SearchResults.Items) { Appointment ItemAppointment = item as Appointment; CalendarItem NewCalendarItem = new CalendarItem(); NewCalendarItem.Start = ItemAppointment.Start; NewCalendarItem.End = ItemAppointment.End; NewCalendarItem.Subject = ItemAppointment.Subject; NewCalendarItem.Source = G510Display.Source.DataManager.ItemSource.Exchange1; CalendarItems.Add(NewCalendarItem); } return(CalendarItems); }
//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); } }
/// <summary> /// 从当前日期开始往前move /// </summary> /// <param name="date"></param> /// <param name="count"></param> public void MoveBeforeDateArchive(DateTime date, int count) { try { SearchFilter.IsLessThanOrEqualTo filter = new SearchFilter.IsLessThanOrEqualTo(ItemSchema.DateTimeReceived, date); SearchFilter.IsGreaterThanOrEqualTo filter2 = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date.AddDays(-1)); SearchFilter.SearchFilterCollection searchFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And, filter, filter2); if (_service != null) { FindFoldersResults aFolders = _service.FindFolders(WellKnownFolderName.MsgFolderRoot, new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Archive"), new FolderView(10)); if (aFolders.Folders.Count == 1) { FolderId archiveFolderId = aFolders.Folders[0].Id; FindItemsResults <Item> findResults = _service.FindItems(WellKnownFolderName.Inbox, searchFilterCollection, new ItemView(count)); Console.WriteLine($"date: {date.ToShortDateString()}, count: {findResults.TotalCount}"); List <ItemId> itemids = new List <ItemId>(); foreach (var item in findResults) { itemids.Add(item.Id); } if (itemids.Count > 0) { _service.MoveItems(itemids, archiveFolderId); Console.WriteLine("move successful!"); } } } } catch (Exception ex) { Console.Write(ex.Message); throw; } }
//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 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); }
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); }
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); } }
public void CleanEmail() { Logger.Debug(new LogInfo(MethodBase.GetCurrentMethod(), "DEB", "Svuoto la caselal di posta")); //cerco tutte le mail già lette SearchFilter sf = new SearchFilter.SearchFilterCollection( LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true) /*, * new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, "jarvis", ContainmentMode.Prefixed, ComparisonMode.IgnoreCase * * )*/); ItemView view = new ItemView(20); // Lanciamo la query FindItemsResults <Item> findResults = this.service.FindItems(WellKnownFolderName.Inbox, sf, view); Logger.Debug(new LogInfo(MethodBase.GetCurrentMethod(), "DEB", string.Format("Trovate {0} nuove mail da cancellare", findResults.TotalCount))); if (findResults.TotalCount > 0) { foreach (var itm in findResults) { itm.Delete(DeleteMode.HardDelete); } } }
private async System.Threading.Tasks.Task GetItemsAsync() { await System.Threading.Tasks.Task.Delay(1000).ConfigureAwait(false); ItemView view = new ItemView(10, 0, OffsetBasePoint.Beginning); view.OrderBy.Add(ItemSchema.DateTimeCreated, SortDirection.Descending); do { contactItems = service.FindItems(WellKnownFolderName.Contacts, view); foreach (Item item in contactItems) { // Do something with the item. if (item is Contact) { Contact cont = (Contact)item; alleAdressen.Add(cont); } } //any more batches? if (contactItems.NextPageOffset.HasValue) { view.Offset = contactItems.NextPageOffset.Value; } }while (contactItems.MoreAvailable); }
protected override void LoadContents() { FindItemsResults <Item> findResults = null; this.ContentItemView.Offset = 0; List <Item> folderItems = new List <Item>(); while ((findResults == null || findResults.MoreAvailable) && folderItems.Count < 1000) { try { this.Cursor = Cursors.WaitCursor; this.currentFolder.Service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. findResults = this.currentFolder.FindItems(this.ContentItemView); } finally { this.Cursor = Cursors.Default; } this.ContentItemView.Offset = this.ContentItemView.Offset + GlobalSettings.FindItemViewSize; foreach (Item item in findResults.Items) { this.AddContentItem(item); } } if (findResults.MoreAvailable && folderItems.Count == 1000) { ErrorDialog.ShowWarning(DisplayStrings.WARN_ITEM_VIEW_COUNT_LIMIT); } }
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 09 //gavdcodebegin 10 private static void ExportContacts(ExchangeService ExService) { FindItemsResults <Item> findResults = ExService.FindItems(WellKnownFolderName.Contacts, new SearchFilter.IsEqualTo(ContactSchema.Surname, "Withphoto"), new ItemView(1)); ItemId myContactId = null; foreach (Item oneItem in findResults) { if (oneItem is Contact foundContact) { myContactId = foundContact.Id; } } PropertySet myPropSet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.MimeContent); Contact contactToExport = Contact.Bind(ExService, myContactId, myPropSet); string vcfFileName = @"C:\Temporary\myContact.vcf"; using (FileStream myContactStream = new FileStream( vcfFileName, FileMode.Create, FileAccess.Write)) { myContactStream.Write(contactToExport.MimeContent.Content, 0, contactToExport.MimeContent.Content.Length); } }
public void ListContacts() { // Get the number of items in the contacts folder. To limit the size of the response, 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 number of items in the Contacts folder or 50, whichever is smaller. int numItems = contactsfolder.TotalCount < 50 ? contactsfolder.TotalCount : 50; // Instantiate the item view with the number of items to retrieve from the Contacts folder. ItemView view = new ItemView(numItems); // To keep the response smaller, request only the display name. view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName); // Request the items in the Contacts folder that have the properties that you selected. FindItemsResults <Item> contactItems = service.FindItems(WellKnownFolderName.Contacts, view); // Display the list of contacts. (Note that there can be a large number of contacts in the Contacts folder.) foreach (Item item in contactItems) { if (item is Contact) { Contact contact = item as Contact; Console.WriteLine(contact.DisplayName); } } }
/// <summary> /// 获取邮件列表 /// </summary> /// <param name="isRead">已读true/未读false</param> /// <param name="count">数量</param> /// <param name="config"></param> /// <returns>邮件列表</returns> public static List <EmailMessage> GetEmailList(bool isRead, int count, ExchangeAdminConfig config) { InitializeEws(config); List <EmailMessage> emails = new List <EmailMessage>(); //创建过滤器 SearchFilter sf = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, isRead); FindItemsResults <Item> findResults = null; try { findResults = Service.FindItems(WellKnownFolderName.Inbox, sf, new ItemView(count)); } catch (Exception ex) { Console.WriteLine(ex.Message); } if (findResults != null) { foreach (Item item in findResults.Items) { EmailMessage email = EmailMessage.Bind(Service, item.Id); emails.Add(email); } } return(emails); }
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"); } }
private static void SearchMailbox(string subject) { //Search filter SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, subject)); FindItemsResults <Item> findResults = _service.FindItems(new FolderId(WellKnownFolderName.Inbox, ExchangeServiceConfig.Username), searchFilter, _view); if (!findResults.Items.Any()) { Console.WriteLine("No messages found!"); return; } var emails = new List <EmailMessage>(); foreach (var item in findResults.Items) { emails.Add((EmailMessage)item); } var properties = (BasePropertySet.FirstClassProperties); _service.LoadPropertiesForItems(emails, properties); //Each email found foreach (var email in emails) { Console.WriteLine("Subject: " + email.Subject + " (de " + email.DateTimeReceived.ToString("dd/MM/yyyy HH:mm:ss") + ")"); DownloadAttachments(email); ExportEmail(email); } }
//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); }
// // GET: /Calendario/ public ActionResult VistaCalendario() { //ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); //service.Credentials = new WebCredentials("*****@*****.**", "Cr1ter14_2015"); //service.AutodiscoverUrl("*****@*****.**", RedirectionUrlValidationCallback); ExchangeService service = (ExchangeService)Session["Office365"]; FindItemsResults <Appointment> foundAppointments = service.FindAppointments(WellKnownFolderName.Calendar, new CalendarView(DateTime.Now, DateTime.Now.AddYears(1), 5)); Calendario calendario = new Calendario(); List <ItemCalendario> icalendario = new List <ItemCalendario>(); foreach (Appointment app in foundAppointments) { ItemCalendario i = new ItemCalendario(); i.Asunto = app.Subject; i.FechaHoraDesde = app.Start; i.FechaHoraHasta = app.End; i.Ubicacion = app.Location; icalendario.Add(i); } calendario.ListaItemCalendario = icalendario; return(PartialView("_VistaCalendario", calendario)); }
public IEnumerable <EmailMessage> ReadEmails(string folderName = "Inbox") { try { ItemView view = new ItemView(50) { PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, EmailMessageSchema.Sender, ItemSchema.HasAttachments, EmailMessageSchema.IsRead, ItemSchema.DateTimeSent, ItemSchema.DateTimeReceived) }; var folders = new string[] { "Inbox", "Sent Items" }; var results = new List <Item>(); foreach (var folderItem in folders) { Folder folder = getFolderByName(folderItem); FindItemsResults <Item> emailMessages = service.FindItems(folder?.Id, view); results.AddRange(emailMessages); } //ICollection<FolderId> folders = new Collection<FolderId> { folder.Id, WellKnownFolderName.Drafts, // WellKnownFolderName.SentItems }; results.Sort(new EmailMessageComparer()); return(results.Cast <EmailMessage>()); } catch (Exception) { throw; } }
private bool UnreadAutopsyRequestExist() { bool result = false; ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.Credentials = new WebCredentials("ypiilab\\histology", "Let'sMakeSlides"); service.TraceEnabled = true; service.TraceFlags = TraceFlags.All; service.AutodiscoverUrl("*****@*****.**", RedirectionUrlValidationCallback); SearchFilter searchFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false); List <SearchFilter> searchFilterCollection = new List <SearchFilter>(); searchFilterCollection.Add(searchFilter); ItemView view = new ItemView(50); view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived); view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending); view.Traversal = ItemTraversal.Shallow; FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, view); if (findResults.Items.Count > 0) { result = true; } return(result); }
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 IEnumerable <Email> getMail(FindItemsResults <Item> findResults, ExchangeService service) { PropertySet propSet = new PropertySet(BasePropertySet.FirstClassProperties); if (bodyFormat.Equals("HTML Format")) { propSet.RequestedBodyType = BodyType.HTML; } else { propSet.RequestedBodyType = BodyType.Text; } foreach (Item result in findResults) { if (result.GetType().ToString().Equals("Microsoft.Exchange.WebServices.Data.EmailMessage")) { EmailMessage message = EmailMessage.Bind(service, result.Id, propSet); Email retMail = new Email(message); message.IsRead = true; message.Update(ConflictResolutionMode.AutoResolve); yield return(retMail); } } }
//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); }
/// <summary> /// gets mail content for the passed in mailid. /// </summary> /// <param name="mailId"></param> /// <returns></returns> public byte[] GetEmailContent(string mailId) { string mailGraphUrl = $"{generalSettings.GraphUrl}/v1.0/me/messages/{mailId}"; string jsonResponse = MakeGetRequestForString(mailGraphUrl); var mail = JsonConvert.DeserializeObject <MailMessage>(jsonResponse); var bytes = (dynamic)null; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013); string accessToken = spoAuthorization.GetExchangeAccessToken(); service.Credentials = new OAuthCredentials(accessToken); service.UseDefaultCredentials = false; service.Url = new Uri(generalSettings.ExchangeServiceURL.ToString()); service.PreAuthenticate = true; service.SendClientLatencies = true; service.EnableScpLookup = false; mailId = mail.Id.Replace("_", "+"); PropertySet propSet = new PropertySet(BasePropertySet.FirstClassProperties); Folder folder = Folder.Bind(service, WellKnownFolderName.Inbox, propSet); SearchFilter filter = new SearchFilter.IsEqualTo(ItemSchema.Id, mailId); FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, filter, new ItemView(1)); foreach (var item in findResults) { item.Load(new PropertySet(EmailMessageSchema.MimeContent)); return(item?.MimeContent?.Content); } return(bytes); }
//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 static string ExchangeConnectorToServiceMailbox() // ← get raw body of the last email contains "PEREODICAL" in subject { string result = ""; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.Credentials = new NetworkCredential("svc_toEusDashboard", "*******", "KL"); service.Url = new Uri("https://hqoutlook.avp.ru/EWS/Exchange.asmx"); FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(1)); foreach (Item item in findResults.Items) { if (item.Subject.Contains("PERIODICAL")) { item.Load(); result = item.Body.Text; return(RawToGoodViewConverter(result)); } else { return("No one item in mailbox contains mail with subject PEREODICAL"); } } return(RawToGoodViewConverter(result)); }
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); }
public List <Item> GetIndoxFormItem(SearchFilter searchFilter, ItemView options = null) { List <Item> items = new List <Item>(); List <Folder> folderIds = new List <Folder>(); FolderView folderView = new FolderView(int.MaxValue); FindFoldersResults findFolderResults = _exchangeService.FindFolders(WellKnownFolderName.Inbox, folderView); if (findFolderResults != null && findFolderResults.TotalCount > 0) { FindItemsResults <Item> parents = Find(searchFilter, options); foreach (Item item in parents) { items.Add(item); } Folder folder = findFolderResults.Folders[0]; FindItemsResults <Item> childrends = _exchangeService.FindItems(folder.Id, searchFilter, options); foreach (Item item in childrends) { items.Add(item); } } return(items); }
private List<Item> GetListItem(FindItemsResults<Item> findResult) { List<Item> items = new List<Item>(); foreach (Item item in findResult) items.Add(item); WriteVerbose(String.Format("Returning {0} items...", items.Count)); return items; }
protected void btnDocumentsSearch_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtKeyword.Text)) { lblErrorMSg.Visible = true; } else { lblErrorMSg.Visible = false; 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); ItemView view = new ItemView(int.MaxValue); Microsoft.Exchange.WebServices.Data.SearchFilter searchFilter = new Microsoft.Exchange.WebServices.Data.SearchFilter.ContainsSubstring(ItemSchema.Body, txtKeyword.Text); instanceResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, view); DataTable table = GetTable(); foreach (var item in instanceResults.Items) { item.Load(); //Console.Clear(); EmailMessage msg = item as EmailMessage; DataRow row = table.NewRow(); string to = string.Empty; foreach (var rec in msg.ToRecipients) to = to + rec.Address + ";"; row["Subject"] = msg.Subject; string body = ExtractHtmlInnerText(msg.Body); if (body.Length > 2000) body = body.Substring(0, 2000); row["Body"] = "From :" + msg.From.Address + "\nTo :" + to + "\nSubject: " + msg.Subject + "\n" + body; row["No.of Attachments"] = msg.Attachments.Count.ToString(); row["Date"] = msg.DateTimeReceived.Date.ToShortDateString(); table.Rows.Add(row); } gvSearchResult.DataSource = table; gvSearchResult.DataBind(); pnlSearchResult.Visible = true; } catch (Exception ex) { lblErrorMSg.Text = "Incorrect Email Settings"; lblErrorMSg.Visible = true; } } }
//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); } }
private static void LogUnreadEmailsCount(FindItemsResults<Item> unreadEmails) { Console.WriteLine("Unread email count: " + unreadEmails.Items.Count); }
private void ProcessResults(FindItemsResults<Item> results) { //_exchangeService.LoadPropertiesForItems(results.Items, _propertySet); //this throws exception foreach (Item item in results.Items) { //item.Load(); //this throws exception if (item.DateTimeReceived > _latestMessageDate) { _latestMessageDate = item.DateTimeReceived + TimeSpan.FromSeconds(1); } EmailMessage email = (EmailMessage)item; if (email.IsRead) continue; string indicator = ""; if (item.Importance == Importance.High) indicator += "!"; if (email.ToRecipients.Count == 0 && email.CcRecipients.Count == 0) indicator += ">>"; SendGrowl(indicator + " " + email.From.Name, item.Subject); } }