Esempio n. 1
0
        private static SearchFilter SetFilter(int intAddHours, string strKeySubject, string strSenderAddress)
        {
            //SearchFilter SearchFilter1 = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "【NA Major Impact】 【P1】 System Down");
            //SearchFilter SearchFilter2 = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "【NA Major Impact】 【P2】 System Slow");
            //SearchFilter SearchFilter3 = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "【Brazil Major Impact】 【P1】 System Down");
            //SearchFilter SearchFilter4 = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "【Brazil Major Impact】 【P2】 System Slow");

            //筛选今天的邮件
            SearchFilter start = new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.DateTimeReceived, Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 00:00:00")).AddHours(intAddHours));
            //SearchFilter end = new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeCreated, Convert.ToDateTime(DateTime.Now.ToString()));
            SearchFilter subject = new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, strKeySubject, ContainmentMode.Substring, ComparisonMode.IgnoreCase);
            // SearchFilter subject = new SearchFilter.ContainsSubstring
            SearchFilter SenderAddress = new SearchFilter.ContainsSubstring(EmailMessageSchema.From, strSenderAddress, ContainmentMode.Substring, ComparisonMode.IgnoreCase);

            //SearchFilter IsRead = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);

            //SearchFilter.SearchFilterCollection secondLevelSearchFilterCollection1 = new SearchFilter.SearchFilterCollection(LogicalOperator.And,
            //                                                                                                               start,
            //                                                                                                               end);

            //SearchFilter.SearchFilterCollection secondLevelSearchFilterCollection2 = new SearchFilter.SearchFilterCollection(LogicalOperator.Or,
            //                                                                                                             SearchFilter1, SearchFilter2, SearchFilter3, SearchFilter4);

            //SearchFilter.SearchFilterCollection firstLevelSearchFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And,
            //                                                                                                                   secondLevelSearchFilterCollection1,
            //                                                                                                                   secondLevelSearchFilterCollection2);

            SearchFilter.SearchFilterCollection firstLevelSearchFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And, start, subject, SenderAddress);


            return(firstLevelSearchFilterCollection);
        }
        public Task <FindItemsResults <Item> > Fetch(TimeSpan timeLimit)
        {
            var selectedTime = DateTime.Now.Add(timeLimit);
            var searchFilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, selectedTime);

            return(_ews.FindItems(WellKnownFolderName.Inbox, searchFilter, new ItemView(50)));
        }
Esempio n. 3
0
        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);
        }
Esempio n. 4
0
 /// <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;
     }
 }
        /// <summary>
        /// Gets first found appointment with specific subject starting from specific date.
        /// </summary>
        /// <param name="service">Exchange service.</param>
        /// <param name="subject">Subject of appointment to search.</param>
        /// <param name="start">Start date.</param>
        /// <returns>Found appointment if any.</returns>
        public static Appointment GetAppointmentBySubject(ExchangeService service, string subject, DateTime start)
        {
            Appointment meeting = null;

            var itemView = new ItemView(3)
            {
                PropertySet = new PropertySet(ItemSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.AppointmentType)
            };

            // Find appointments by subject.
            var substrFilter = new SearchFilter.ContainsSubstring(ItemSchema.Subject, subject);
            var startFilter  = new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, start);

            var filterList = new List <SearchFilter>
            {
                substrFilter,
                startFilter
            };

            var calendarFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, filterList);

            var results = service.FindItems(WellKnownFolderName.Calendar, calendarFilter, itemView);

            if (results.Items.Count == 1)
            {
                meeting = results.Items[0] as Appointment;
            }

            return(meeting);
        }
Esempio n. 6
0
        //根据时间范围过滤:message里的日期格式 "2017/08/17 00:00:00;

        public static SearchFilter filterByTimeRange(string beginDate)
        {
            beginDate += " 00:00:00";
            DateTime     begindt     = Util.convertToDateTime(beginDate);
            SearchFilter searcFilter = new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.DateTimeReceived, begindt);

            return(searcFilter);
        }
Esempio n. 7
0
        /// <summary>
        ///从当前日期开始往后move
        /// </summary>
        /// <param name="date"></param>
        /// <param name="count"></param>
        public void MoveAfterDateArchive(DateTime date, int count, int days)
        {
            try
            {
                SearchFilter.IsLessThanOrEqualTo    filter  = new SearchFilter.IsLessThanOrEqualTo(ItemSchema.DateTimeReceived, date.AddDays(days));
                SearchFilter.IsGreaterThanOrEqualTo filter2 = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);
                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)
                        {
                            Console.WriteLine("moving ... ...");
                            Stopwatch sw = new Stopwatch();
                            sw.Start();
                            _service.MoveItems(itemids, archiveFolderId);
                            sw.Stop();
                            //new Timer(new TimerCallback(timer_Elapsed), null, 0, 30000);

                            Console.WriteLine($"move successful after {sw.ElapsedMilliseconds} ms, then sleep 10s ...");

                            System.Threading.Thread.Sleep(10000); //30s
                        }
                    }
                }
            }
            catch (ServiceRequestException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("try again...");
                MoveAfterDateArchive(date, count, days);
            }
            catch (ServiceRemoteException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("sleep 120s ...");
                System.Threading.Thread.Sleep(120000); //120s
                Console.WriteLine("try again...");
                MoveAfterDateArchive(date, count, days);
            }
            catch (Exception)
            {
                throw;
            }
        }
        public static FindItemsResults <Item> FindResults(ExchangeService exchange, TimeSpan times)
        {
            var date = DateTime.Now.Add(times);

            var filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);

            var result = exchange.FindItems(WellKnownFolderName.Inbox, filter, new ItemView(50));

            return(result);
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            // Create an instance of the custom URL redirection validator.
            UrlValidator validator = new UrlValidator();

            // Get the user's email address and password from the console.
            IUserData userData = UserDataFromConsole.GetUserData();

            // Create an ExchangeService object with the user's credentials.
            ExchangeService myService = new ExchangeService();

            myService.Credentials = new NetworkCredential(userData.EmailAddress, userData.Password);


            Console.WriteLine("Getting EWS URL using custom validator...");

            // Call the Autodisocer service with the custom URL validator.
            myService.AutodiscoverUrl(userData.EmailAddress, validator.ValidateUrl);
            TimeSpan    ts              = new TimeSpan(0, -1, 0, 0);
            DateTime    date            = DateTime.Now.Add(ts);
            PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);

            itempropertyset.RequestedBodyType = BodyType.Text;
            SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);

            if (myService != null)
            {
                ItemView itemview = new ItemView(1000);
                itemview.PropertySet = itempropertyset;

                FindItemsResults <Item> findResults = myService.FindItems(WellKnownFolderName.Inbox, filter, itemview);
                List <News>             newsList    = new List <News>();
                if (findResults.Items.Count > 0)
                {
                    foreach (Item item in findResults)
                    {
                        item.Load(itempropertyset);
                        string   Body      = item.Body.Text.ToString().Replace("\r\n", "");
                        string[] emailBody = Body.Split('|');
                        Dictionary <string, string> dictionary = new Dictionary <string, string>();
                        foreach (var item11 in emailBody)
                        {
                            dictionary.Add(item11.Substring(0, item11.LastIndexOf(':')).Trim(), item11.Substring(item11.LastIndexOf(':') + 1).Trim());
                        }
                        dictionary.Add("IsPublish", item.Importance.ToString() == "High" ? "True" : "False");
                        var test = helper.GetObject <News>(dictionary);
                        newsList.Add(test);
                    }
                    Generation.process(newsList);
                }
            }
        }
Esempio n. 10
0
 public void MoveBeforeDateArchive(DateTime date, int count, int days)
 {
     try
     {
         SearchFilter.IsLessThanOrEqualTo    beginfilter            = new SearchFilter.IsLessThanOrEqualTo(ItemSchema.DateTimeReceived, date);
         SearchFilter.IsGreaterThanOrEqualTo endfilter              = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date.AddDays(-1 * days));
         SearchFilter.SearchFilterCollection searchFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And, beginfilter, endfilter);
         if (_service != null)
         {
             FindItemsResults <Item> findResults = _service.FindItems(WellKnownFolderName.Inbox, searchFilterCollection, new ItemView(count));
             message = $"date: {date.ToShortDateString()}, count: {findResults.TotalCount}" + (findResults.TotalCount > 0 ? ", moving..." : ", skip...");
             List <ItemId> itemids = new List <ItemId>();
             foreach (var item in findResults)
             {
                 itemids.Add(item.Id);
             }
             if (itemids.Count > 0)
             {
                 _service.MoveItems(itemids, archiveFolderId);
                 message = $"move successful, then sleep 10s ...";
                 Thread.Sleep(10000); //10s
             }
             else
             {
                 Thread.Sleep(500); //1s
             }
         }
         else
         {
             message = "can't connect to server.";
         }
     }
     catch (ServiceRequestException ex)
     {
         message = ex.Message;
         message = "try again...";
         MoveBeforeDateArchive(date, count, days);
     }
     catch (ServerBusyException ex)
     {
         message = ex.Message;
         message = "pause 120s ...";
         Thread.Sleep(120000); //120s
         message = "try again...";
         MoveBeforeDateArchive(date, count, days);
     }
     catch (Exception ex)
     {
         message = ex.Message;
         throw;
     }
 }
Esempio n. 11
0
        public FindItemsResults <Item> GetNewEmails(string userName, string password, DateTime searchdate)
        {
            Login(userName, password);

            SearchFilter greaterthanfilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, searchdate);
            //SearchFilter lessthanfilter = new SearchFilter.IsLessThan(ItemSchema.DateTimeReceived, searchdate.AddDays(1));
            SearchFilter filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, greaterthanfilter);

            ItemView view = new ItemView(100000);
            FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, filter, view);

            return(findResults);
        }
        public void IsGreaterThanOrEqualTo()
        {
            SearchFilter filter = new SearchFilter.IsGreaterThanOrEqualTo(
                MessageObjectSchema.CreatedDateTime,
                "20-02-19");

            Assert.AreEqual(
                filter.FilterOperator,
                FilterOperator.ge);

            Assert.AreEqual(
                "$filter=CreatedDateTime ge 20-02-19"
                , filter.Query);
        }
Esempio n. 13
0
        /// <summary>
        /// 过滤器
        /// </summary>
        /// <returns></returns>
        private static SearchFilter SetFilter()
        {
            List <SearchFilter> searchFilterCollection = new List <SearchFilter>();
            //searchFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
            //searchFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true));
            //筛选今天的邮件
            SearchFilter start = new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.DateTimeCreated, Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 00:00:00")));
            SearchFilter end   = new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeCreated, Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59")));

            searchFilterCollection.Add(start);
            searchFilterCollection.Add(end);
            SearchFilter filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection.ToArray());

            return(filter);
        }
Esempio n. 14
0
        public void GetMessages()
        {
            var value  = ConfigurationManager.AppSettings["name"];
            var ts     = new TimeSpan(-5, 0, 0, 0);
            var date   = DateTime.Now.Add(ts);
            var filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);

            if (_exchange == null)
            {
                return;
            }
            var findResults = _exchange.FindItems(WellKnownFolderName.Inbox, filter, new ItemView(1000));

            if (findResults != null)
            {
                InitializeView();
                foreach (var item in findResults)
                {
                    // TBD: Any custom business logic, in this case I am checking if the message has an attachment and the
                    // person who replied last in the message thread is not the name from configuration value
                    if (item != null && (!item.HasAttachments ||
                                         item.LastModifiedName.Contains(value)))
                    {
                        continue;
                    }
                    if (item == null)
                    {
                        continue;
                    }
                    var listitem = new ListViewItem(new[]
                    {
                        item.LastModifiedName, item.Subject, item.LastModifiedTime.ToString(CultureInfo.CurrentCulture), item.Size.ToString(),
                        item.Id.ToString()
                    });
                    listView1?.Items.Add(listitem);
                }
                if (findResults.Items.Count <= 0)
                {
                    listView1?.Items.Add("No Messages found!!");
                }
            }
            else
            {
                throw new ArgumentNullException(nameof(findResults));
            }
        }
Esempio n. 15
0
        public FindItemsResults <Item> GetNewEmails(string userName, string password)
        {
            Login(userName, password);

            IEnumerable <Email> emails = _facade.EmailRepo.GetAll();
            var      latest            = emails.OrderByDescending(m => m.ReceivedDate).FirstOrDefault();
            DateTime searchdate        = latest.ReceivedDate.AddSeconds(1);


            SearchFilter greaterthanfilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, searchdate);
            //SearchFilter lessthanfilter = new SearchFilter.IsLessThan(ItemSchema.DateTimeReceived, searchdate.AddDays(1));
            SearchFilter filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, greaterthanfilter);

            ItemView view = new ItemView(100000);
            FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, filter, view);

            return(findResults);
        }
Esempio n. 16
0
        /// <inheritdoc />
        protected override void Execute(CodeActivityContext context)
        {
            var service = ExchangeHelper.GetService(context.GetValue(OrganizerPassword), context.GetValue(ExchangeUrl), context.GetValue(OrganizerEmail));

            var start = context.GetValue(AppointmentDateFrom);
            var appointmentSubject = context.GetValue(AppointmentSubject);

            var amount = context.GetValue(Amount);

            var itemView = new ItemView(amount)
            {
                PropertySet = new PropertySet(
                    ItemSchema.Subject,
                    AppointmentSchema.Start,
                    ItemSchema.DisplayTo,
                    AppointmentSchema.AppointmentType,
                    ItemSchema.DateTimeSent)
            };

            // Find appointments by subject.
            var substrFilter = new SearchFilter.ContainsSubstring(ItemSchema.Subject, appointmentSubject);
            var startFilter  = new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, start);

            var filterList = new List <SearchFilter>
            {
                substrFilter,
                startFilter
            };

            var calendarFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, filterList);

            var results = service.FindItems(WellKnownFolderName.SentItems, calendarFilter, itemView);

            var history = results.Select(item => new NotifyHistory
            {
                Subject = item.Subject,
                SentOn  = item.DateTimeSent,
                SentTo  = item.DisplayTo
            }).ToArray();

            context.SetValue(SentNotificationsHistory, history);
        }
Esempio n. 17
0
        private void GetEmails()
        {
            TimeSpan ts   = new TimeSpan(-1, 0, 0, 0);
            DateTime date = DateTime.Now.Add(ts);

            SearchFilter.IsGreaterThanOrEqualTo filter =
                new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);
            //    new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.IsRead, false);

            FindItemsResults <Item> findResults = _exchange.FindItems(WellKnownFolderName.Inbox, filter,
                                                                      new ItemView(50));

            foreach (Item item in findResults)
            {
                EmailMessage message = EmailMessage.Bind(_exchange, item.Id);
            }
            if (findResults.Items.Count <= 0)
            {
            }
        }
        public void ForwardedAppointmentTest()
        {
            DateTime.TryParse("06-July-2019", out var testStartDate);

            var service = ExchangeHelper.GetService(ExchangePass, ExchangeServerUrl, ExchangeLogin);

            var itemView = new ItemView(10)
            {
                PropertySet = new PropertySet(ItemSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.AppointmentType)
            };

            // Find appointments by subject.
            var substrFilter = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "AppointmentAttachmentCheck1");
            var startFilter  = new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, testStartDate);

            var filterList = new List <SearchFilter>
            {
                substrFilter,
                startFilter
            };

            var calendarFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, filterList);

            var results = service.FindItems(WellKnownFolderName.SentItems, calendarFilter, itemView);

            foreach (var cur in results)
            {
                var item      = Item.Bind(service, cur.Id, new PropertySet(ItemSchema.Subject, AppointmentSchema.Start, ItemSchema.DisplayTo, AppointmentSchema.AppointmentType, ItemSchema.DateTimeSent));
                var displayTo = item.DisplayTo;

                Console.WriteLine(displayTo);
                Console.WriteLine(item.DateTimeSent);
            }

            Assert.AreEqual("AppointmentAttachmentCheck1", "AppointmentAttachmentCheck1");
        }
Esempio n. 19
0
        private void btnRead_Click(object sender, EventArgs e)
        {
            ConnectToExchangeServer();

            TimeSpan ts   = new TimeSpan(0, -24, 0, 0);
            DateTime date = DateTime.Now.Add(ts);

            SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);

            if (exchange != null)
            {
                FindItemsResults <Item> findResults = exchange.FindItems(WellKnownFolderName.Inbox, filter, new ItemView(50));

                if (findResults != null)
                {
                    foreach (Item item in findResults)
                    {
                        EmailMessage message  = EmailMessage.Bind(exchange, item.Id);
                        ListViewItem listitem = new ListViewItem(new[]
                        {
                            message.DateTimeReceived.ToString(), message.From.Name.ToString() + "(" + message.From.Address.ToString() + ")", message.Subject, ((message.HasAttachments) ? "Var" : "Yok"), HtmlToPlainText(message.Body), message.Id.ToString()
                        });
                        lstMsg.Items.Add(listitem);
                    }

                    if (findResults.Items.Count <= 0)
                    {
                        lstMsg.Items.Add("Mail Bulunamadı!!");
                    }
                }
                else
                {
                    MessageBox.Show("Hatalı sunucu!");
                }
            }
        }
        /// <summary>
        /// This method creates and sets the search folder.
        /// </summary>
        private static SearchFolder CreateSearchFolder(ExchangeService service,
                                                       Dictionary <PropertyDefinition, String> filters, String displayName)
        {
            if (service == null)
            {
                return(null);
            }

            SearchFilter.SearchFilterCollection filterCollection =
                new SearchFilter.SearchFilterCollection(LogicalOperator.And);

            // We only search the nearest 30 days emails.
            DateTime     startDate       = DateTime.Now.AddDays(-30);
            DateTime     endDate         = DateTime.Now;
            SearchFilter startDateFilter =
                new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.DateTimeCreated, startDate);
            SearchFilter endDateFilter =
                new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeCreated, endDate);

            filterCollection.Add(startDateFilter);
            filterCollection.Add(endDateFilter);

            SearchFilter itemClassFilter =
                new SearchFilter.IsEqualTo(EmailMessageSchema.ItemClass, "IPM.Note");

            filterCollection.Add(itemClassFilter);

            // Set the other filters.
            if (filters != null)
            {
                foreach (PropertyDefinition property in filters.Keys)
                {
                    SearchFilter searchFilter =
                        new SearchFilter.ContainsSubstring(property, filters[property]);
                    filterCollection.Add(searchFilter);
                }
            }

            FolderId folderId = new FolderId(WellKnownFolderName.Inbox);

            Boolean      isDuplicateFoler = true;
            SearchFilter duplicateFilter  = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, displayName);
            SearchFolder searchFolder     =
                GetFolder(service, duplicateFilter, WellKnownFolderName.SearchFolders) as SearchFolder;

            // If there isn't the specific search folder, we create a new one.
            if (searchFolder == null)
            {
                searchFolder     = new SearchFolder(service);
                isDuplicateFoler = false;
            }
            searchFolder.SearchParameters.RootFolderIds.Add(folderId);
            searchFolder.SearchParameters.Traversal    = SearchFolderTraversal.Shallow;
            searchFolder.SearchParameters.SearchFilter = filterCollection;

            if (isDuplicateFoler)
            {
                searchFolder.Update();
            }
            else
            {
                searchFolder.DisplayName = displayName;

                searchFolder.Save(WellKnownFolderName.SearchFolders);
            }

            return(searchFolder);
        }
Esempio n. 21
0
        public static void DownloadAttachement(string mailaddress, string subject, string outfolder, string logFile, bool logVerbose)
        {
            ExchangeService exservice = new ExchangeService(ExchangeVersion.Exchange2010_SP2);

            exservice.UseDefaultCredentials = true;
            exservice.AutodiscoverUrl(mailaddress);
            FolderId folderid = new FolderId(WellKnownFolderName.Inbox, mailaddress);
            Folder   inbox    = Folder.Bind(exservice, folderid);

            SearchFilter.SearchFilterCollection sfcollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
            SearchFilter.IsEqualTo sfir = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
            sfcollection.Add(sfir);
            SearchFilter.IsEqualTo sfha = new SearchFilter.IsEqualTo(EmailMessageSchema.HasAttachments, true);
            sfcollection.Add(sfha);
            //SearchFilter.ContainsSubstring sffrm = new SearchFilter.ContainsSubstring(EmailMessageSchema.From, from); No longer needed as multiple addresses will send emails.
            //sfcollection.Add(sffrm);
            SearchFilter.IsGreaterThanOrEqualTo sfdt = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, DateTime.Now.AddDays(-31));
            sfcollection.Add(sfdt);
            SearchFilter.ContainsSubstring sfsub = new SearchFilter.ContainsSubstring(ItemSchema.Subject, subject);
            sfcollection.Add(sfsub);

            //Initialise loop variables
            int  pagesize  = 100;
            int  offset    = 0;
            bool moreitems = true;

            //Load emails and download attachments
            while (moreitems)
            {
                ItemView view = new ItemView(pagesize, offset, OffsetBasePoint.Beginning);
                FindItemsResults <Item> finditems = inbox.FindItems(sfcollection, view);

                if (finditems.TotalCount > 0)
                {
                    Log.message(LogEntryType.INFO, "DBAidExtractor", "Found " + finditems.TotalCount.ToString() + " mail items.", logFile);
                }
                else
                {
                    Log.message(LogEntryType.INFO, "DBAidExtractor", "No more mail items found.", logFile);
                    break;
                }

                foreach (EmailMessage item in finditems.Items)
                {
                    try
                    {
                        item.Load();

                        foreach (FileAttachment attach in item.Attachments)
                        {
                            attach.Load();
                            FileStream file = null;

                            try
                            {
                                file = new System.IO.FileStream(Path.Combine(outfolder, attach.Name), FileMode.Create);
                                file.Write(attach.Content, 0, attach.Content.Length);
                            }
                            catch (Exception ex)
                            {
                                Log.message(LogEntryType.WARNING, "DBAidExtractor", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
                                continue;
                            }
                            finally
                            {
                                file.Flush();
                                file.Close();
                            }

                            Log.message(LogEntryType.INFO, "DBAidExtractor", "Downloaded Attachment:" + outfolder + "\\" + attach.Name, logFile);
                        }

                        item.IsRead = true;
                        item.Update(ConflictResolutionMode.AlwaysOverwrite);
                    }
                    catch (Exception ex)
                    {
                        Log.message(LogEntryType.WARNING, "DBAidExtractor", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
                        continue;
                    }
                }

                if (finditems.MoreAvailable == false)
                {
                    moreitems = false;
                }
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Create a search filter for filtering items based on equality comparisons of property values.
        /// </summary>
        /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param>
        private static void UseAnEqualitySearchFilter(ExchangeService service)
        {
            // The IsGreaterThan filter determines whether the value of a property is greater than a specific value.
            // This filter instance filters on the DateTimeReceived property, where the value is greater than a month ago.
            SearchFilter.IsGreaterThan isGreaterThan = new SearchFilter.IsGreaterThan(EmailMessageSchema.DateTimeReceived, DateTime.Now.AddMonths(-1));

            // The IsGreaterThanOrEqualTo filter determines whether the value of a property is greater than or equal to a specific value.
            // This filter instance filters on the DateTimeCreated property, where the value is greater than or equal to a week ago.
            SearchFilter.IsGreaterThanOrEqualTo isGreaterThanOrEqualTo = new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.DateTimeCreated, DateTime.Now.AddDays(-7));

            // The IsLessThan filter determines whether the value of a property is less than a specific value.
            // This filter instance filters on the DateTimeReceived property, where the value is less than the time an hour ago.
            SearchFilter.IsLessThan isLessThan = new SearchFilter.IsLessThan(EmailMessageSchema.DateTimeReceived, DateTime.Now.AddHours(-1));

            // The IsLessThanOrEqualTo filter determines whether the value of a property is less than or equal to a specific value.
            // This filter instance filters on the DateTimeCreated property, where the value is less than or equal to the time two days ago.
            SearchFilter.IsLessThanOrEqualTo isLessThanOrEqualTo = new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeCreated, DateTime.Now.AddDays(-2));

            // The IsEqualTo filter determines whether the value of a property is equal to a specific value.
            // This filter instance filters on the Importance property where it is set to Normal.
            SearchFilter.IsEqualTo isEqualTo = new SearchFilter.IsEqualTo(EmailMessageSchema.Importance, Importance.Normal);

            // The IsNotEqualTo filter determines whether the value of a property is not equal to a specific value.
            // This filter instance filters on the IsRead property, where it is not set to true.
            SearchFilter.IsNotEqualTo isNotEqualTo = new SearchFilter.IsNotEqualTo(EmailMessageSchema.IsRead, true);

            // Create a search filter collection that will filter based on an item's Importance and IsRead flag.
            // Both conditions must pass for an item to be returned in a result set.
            SearchFilter.SearchFilterCollection secondLevelSearchFilterCollection1 = new SearchFilter.SearchFilterCollection(LogicalOperator.And,
                                                                                                                             isEqualTo,
                                                                                                                             isNotEqualTo);

            // Create a search filter collection that will filter based on an item's DateTimeCreated and DateTimeReceived properties.
            // All four conditions must pass for an item to be returned in a result set.
            SearchFilter.SearchFilterCollection secondLevelSearchFilterCollection2 = new SearchFilter.SearchFilterCollection(LogicalOperator.And,
                                                                                                                             isGreaterThan,
                                                                                                                             isGreaterThanOrEqualTo,
                                                                                                                             isLessThan,
                                                                                                                             isLessThanOrEqualTo);

            // The SearchFilterCollection contains a collection of search filter collections. Items must pass the search conditions
            // of either collection for an item to be returned in a result set.
            SearchFilter.SearchFilterCollection firstLevelSearchFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.Or,
                                                                                                                           secondLevelSearchFilterCollection1,
                                                                                                                           secondLevelSearchFilterCollection2);


            // Create a nonpaged view and add properties to the results set.
            ItemView view = new ItemView(10);

            view.PropertySet = new PropertySet(EmailMessageSchema.Subject,
                                               EmailMessageSchema.DateTimeCreated,
                                               EmailMessageSchema.DateTimeReceived,
                                               EmailMessageSchema.Importance,
                                               EmailMessageSchema.IsRead);

            try
            {
                // Search the Inbox based on the ItemView and the SearchFilterCollection. This results in a FindItem operation call
                // to EWS.
                FindItemsResults <Item> results = service.FindItems(WellKnownFolderName.Inbox,
                                                                    firstLevelSearchFilterCollection,
                                                                    view);

                foreach (Item item in results.Items)
                {
                    Console.WriteLine("\r\nSubject:\t\t{0}", item.Subject);
                    Console.WriteLine("DateTimeCreated:\t{0}", item.DateTimeCreated.ToShortDateString());
                    Console.WriteLine("DateTimeReceived:\t{0}", item.DateTimeReceived.ToShortDateString());
                    Console.WriteLine("Importance:\t\t{0}", item.Importance.ToString());
                    Console.WriteLine("IsRead:\t\t\t{0}", (item as EmailMessage).IsRead.ToString());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: {0}", ex.Message);
            }
        }
Esempio n. 23
0
        private void button8_Click(object sender, EventArgs e)
        {
            lstMsg.Visible = false;
            if (textBox3.Text == "" || textBox2.Text == "")
            {
                MessageBox.Show("Lütfen mail adresi ve şifrenizi giriniz.");
            }
            else
            {
                if (Regex.IsMatch(textBox3.Text, @"(@)"))
                {
                    this.Size     = new Size(1454, 664);
                    this.Location = new Point(50, 50);
                    username      = textBox3.Text.Split('@')[0];
                    domain        = textBox3.Text.Split('@')[1];

                    lblMsg.Visible = true;
                    i = 0;
                    lstMsg.Items.Clear();
                    if (domain == "hotmail.com" || domain == "std.yildiz.edu.tr")
                    {
                        ConnectToExchangeServer();
                        TimeSpan ts   = new TimeSpan(0, -24, 0, 0);
                        DateTime date = DateTime.Now.Add(ts);
                        SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);

                        if (exchange != null)
                        {
                            PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
                            itempropertyset.RequestedBodyType = BodyType.Text;
                            ItemView itemview = new ItemView(1000);
                            itemview.PropertySet = itempropertyset;

                            //FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, "subject:TODO", itemview);

                            lstMsg.Width  = 1170;
                            lstMsg.Height = 450;
                            button8.Text  = "Yenile";
                            try
                            {
                                FindItemsResults <Item> findResults = exchange.FindItems(WellKnownFolderName.Inbox, filter, new ItemView(100));
                                foreach (Item item in findResults)
                                {
                                    lstMsg.Visible = true;
                                    item.Load(itempropertyset);
                                    String content = item.Body;
                                    icerikler[i] = content;


                                    var input = new Input {
                                        Text = content
                                    };
                                    var prediction = predictor.Predict(input);


                                    double skor = Cast(prediction.Probability, typeof(double));

                                    String durum;
                                    if ((Convert.ToBoolean(prediction.Prediction) ? "Spam" : "Not spam") == "Spam")
                                    {
                                        durum = "YES";
                                    }
                                    else
                                    {
                                        durum = "NO";
                                    }

                                    EmailMessage message = EmailMessage.Bind(exchange, item.Id);
                                    basliklar[i] = message.Subject;
                                    i++;
                                    ListViewItem listitem = new ListViewItem(new[]
                                    {
                                        message.DateTimeReceived.ToString(), message.From.Name.ToString() + "(" + message.From.Address.ToString() + ")", message.Subject,
                                        content, durum, skor.ToString("N2")
                                    });

                                    lstMsg.Items.Add(listitem);
                                }
                                if (findResults.Items.Count <= 0)
                                {
                                    lstMsg.Items.Add("Yeni Mail Bulunamadı.!!");
                                }
                                colorListcolor(lstMsg);
                            }
                            catch
                            {
                                MessageBox.Show("Mail adresi veya şifre yanlış.");
                                textBox3.Text  = "";
                                textBox2.Text  = "";
                                lblMsg.Text    = "";
                                lblMsg.Visible = false;
                                button8.Text   = "Giriş";
                                Screen screen = Screen.FromControl(this);

                                Rectangle workingArea = screen.WorkingArea;
                                this.Location = new Point()
                                {
                                    X = Math.Max(workingArea.X, workingArea.X + (workingArea.Width - this.Width) / 2),
                                    Y = Math.Max(workingArea.Y, workingArea.Y + (workingArea.Height - this.Height) / 2)
                                };
                            }
                        }
                    }
                    else if (domain == "gmail.com")
                    {
                        lblMsg.Text = "IMAP Server'a bağlanılıyor....";
                        lblMsg.Refresh();
                        try
                        {
                            IC          = new ImapClient("imap.gmail.com", textBox3.Text, textBox2.Text, AuthMethods.Login, 993, true);
                            lblMsg.Text = "IMAP Server'a bağlandı.\nGünlük Mailler Gösteriliyor.";
                            lblMsg.Refresh();
                            IC.SelectMailbox("INBOX");
                            int mailCount = IC.GetMessageCount();
                            mailCount--;
                            var      Email        = IC.GetMessage(mailCount);
                            DateTime localDate    = DateTime.Now;
                            TimeSpan baseInterval = new TimeSpan(24, 0, 0);
                            var      value        = localDate.Subtract(Email.Date);

                            lstMsg.Visible = true;
                            lstMsg.Width   = 1170;
                            lstMsg.Height  = 450;
                            button8.Text   = "Yenile";

                            while (TimeSpan.Compare(baseInterval, value) == 1)
                            {
                                basliklar[i] = Email.Subject.ToString();
                                icerikler[i] = Email.Body.ToString();
                                i++;


                                var input = new Input {
                                    Text = Email.Body
                                };
                                var prediction = predictor.Predict(input);

                                double skor = Cast(prediction.Probability, typeof(double));

                                String durum;
                                if ((Convert.ToBoolean(prediction.Prediction) ? "Spam" : "Not spam") == "Spam")
                                {
                                    durum = "YES";
                                }
                                else
                                {
                                    durum = "NO";
                                }
                                var          content  = Email.Body.ToString();
                                ListViewItem listitem = new ListViewItem(new[]
                                {
                                    Email.Date.ToString(), Email.From.Address.ToString(), Email.Subject.ToString(),
                                    content, durum, skor.ToString("N2")
                                });

                                lstMsg.Items.Add(listitem);
                                //MessageBox.Show(Email.Subject.ToString());
                                mailCount--;
                                Email = IC.GetMessage(mailCount);
                                value = localDate.Subtract(Email.Date);
                            }
                            colorListcolor(lstMsg);
                        }
                        catch
                        {
                            MessageBox.Show("Lütfen email güvenlik ayarlarından Daha az güvenli uygulamalara izin ver: AÇIK yapınız.");
                        }
                    }
                    else
                    {
                        MessageBox.Show("Geçersiz bir domain ismi girdiniz.Lütfen kontrol edin!");
                    }
                }
                else
                {
                    MessageBox.Show("Lütfen doğru bir mail formatı giriniz.");
                }
            }
        }
Esempio n. 24
0
        // Go connect to afolder and get the items
        public static List <Item> GetItems(ExchangeService service, string strFolder)
        {
            Folder                  fld         = null;
            int                     iOffset     = 0;
            int                     iPageSize   = 500;
            bool                    bMore       = true;
            List <Item>             lItems      = new List <Item>();
            FindItemsResults <Item> findResults = null;
            DateTime                dtNow       = DateTime.Now;
            DateTime                dtBack      = dtNow.AddHours(-24);

            if (bStartDate) // default is 24 hours ago on the date, but the user can specify longer ago than that if they wish.
            {
                dtBack = dtStartDate;
            }

            SearchFilter.ContainsSubstring      apptFilter     = new SearchFilter.ContainsSubstring(ItemSchema.ItemClass, "IPM.Appointment");
            SearchFilter.IsGreaterThanOrEqualTo modifiedFilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.LastModifiedTime, dtBack);
            SearchFilter.SearchFilterCollection multiFilter    = new SearchFilter.SearchFilterCollection(LogicalOperator.And, apptFilter, modifiedFilter);

            if (strFolder == "Calendar")
            {
                try
                {
                    // Here's where it connects to the Calendar
                    fld    = Folder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());
                    fldCal = fld;
                }
                catch (ServiceResponseException ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("");
                    Console.WriteLine("Could not connect to this user's mailbox or Calendar folder.");
                    Console.WriteLine(ex.Message);
                    Console.ResetColor();
                    return(null);
                }
            }
            else if (strFolder == "Purges")
            {
                try
                {
                    // Here's where it connects to Purges
                    fld       = Folder.Bind(service, WellKnownFolderName.RecoverableItemsPurges, new PropertySet());
                    fldPurges = fld;
                }
                catch (ServiceResponseException ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("");
                    Console.WriteLine("Could not connect to this user's mailbox or Purges folder.");
                    Console.WriteLine(ex.Message);
                    Console.ResetColor();
                    return(null);
                }
            }
            else
            {
                Console.WriteLine("Not Purges or Calendar - no connection.");
                return(null);
            }

            // if we're in then we get here
            // creating a view with props to request / collect
            ItemView cView = new ItemView(iPageSize, iOffset, OffsetBasePoint.Beginning);
            List <ExtendedPropertyDefinition> propSet = new List <ExtendedPropertyDefinition>();

            DoProps(ref propSet);
            cView.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties);
            foreach (PropertyDefinitionBase pdbProp in propSet)
            {
                cView.PropertySet.Add(pdbProp);
            }

            if (strFolder == "Purges")
            {
                cView.OrderBy.Add(ItemSchema.LastModifiedTime, SortDirection.Descending);
                while (bMore)
                {
                    findResults = fld.FindItems(multiFilter, cView);

                    foreach (Item item in findResults.Items)
                    {
                        lItems.Add(item);
                    }

                    bMore = findResults.MoreAvailable;
                    if (bMore)
                    {
                        cView.Offset += iPageSize;
                    }
                }
            }
            else // Calendar folder - don't need to do the search filtering here...
            {
                while (bMore)
                {
                    findResults = fld.FindItems(cView);

                    foreach (Item item in findResults.Items)
                    {
                        lItems.Add(item);
                    }

                    bMore = findResults.MoreAvailable;
                    if (bMore)
                    {
                        cView.Offset += iPageSize;
                    }
                }
            }

            return(lItems);
        }
Esempio n. 25
0
        public static void GetMails()
        {
            try
            {
                //TimeSpan ts = new TimeSpan(0, -1, 0, 0);
                TimeSpan ts   = new TimeSpan(0, 0, -5, 0);
                DateTime date = DateTime.Now.Add(ts);
                //ExchangeService exchange = new ExchangeService(ExchangeVersion.Exchange2010);
                ExchangeService exchange = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
                //exchange.Credentials = new WebCredentials("Domain\\Username", @"Password");
                exchange.Credentials = new WebCredentials("Domain\\myusername", @"mypassword");
                //Uri - https://mail.comanyname.com/EWS/Exchange.asmx
                exchange.Url          = new Uri("https://mail.uhc.com/EWS/Exchange.asmx");
                exchange.TraceEnabled = true;
                exchange.TraceFlags   = TraceFlags.All;
                exchange.AutodiscoverUrl("*****@*****.**", RedirectionCallback);
                SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);
                Service1.Log("calling service");
                FindItemsResults <Item> findResults = exchange.FindItems(WellKnownFolderName.Inbox, filter, new ItemView(50));

                bool RedirectionCallback(string url)
                {
                    return(url.ToLower().StartsWith("https://"));
                }
                foreach (Item item in findResults.Items)
                {
                    GetAttachmentsFromEmail(exchange, item.Id, item.Subject);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
                Service1.Log(ex.Message);
            }
            void GetAttachmentsFromEmail(ExchangeService service, ItemId itemId, String subject)
            {
                // Bind to an existing message item and retrieve the attachments collection.
                // This method results in an GetItem call to EWS.
                EmailMessage message = EmailMessage.Bind(service, itemId, new PropertySet(ItemSchema.Attachments));

                // Iterate through the attachments collection and load each attachment.

                Service1.Log("Downloading attachments");
                foreach (Attachment attachment in message.Attachments)
                {
                    if (attachment is FileAttachment)
                    {
                        FileAttachment fileAttachment = attachment as FileAttachment;
                        // fileAttachment.Load("Put mails attachments" + fileAttachment.Name);
                        fileAttachment.Load("C:\\MailAttachments\\" + fileAttachment.Name);
                        //System.IO.FileInfo fi = new System.IO.FileInfo("C:\\Mails\\" + fileAttachment.Name);
                        //if (fi.Exists)
                        //{
                        //    // Move file with a new name. Hence renamed.
                        //    fi.MoveTo(@"C:\\Mails\\" + subject);
                        //    Console.WriteLine("File Renamed.");
                        //}
                        Console.WriteLine("File attachment name: " + fileAttachment.Name);
                    }
                    else // Attachment is an item attachment.
                    {
                        ItemAttachment itemAttachment = attachment as ItemAttachment;
                        // Load attachment into memory and write out the subject.
                        // This does not save the file like it does with a file attachment.
                        // This call results in a GetAttachment call to EWS.
                        itemAttachment.Load();
                        Console.WriteLine("Item attachment name: " + itemAttachment.Name);
                        Service1.Log("Item attachment name: " + itemAttachment.Name);
                    }
                }
            }
        }