示例#1
0
        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);
        }
        public void IsGreaterThanTest()
        {
            SearchFilter filter = new SearchFilter.IsGreaterThan(
                MessageObjectSchema.CreatedDateTime,
                "2019-02-19");

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

            Assert.AreEqual(
                "$filter=CreatedDateTime gt 2019-02-19"
                , filter.Query);
        }
        public void TestSearchFilterCollection()
        {
            SearchFilter lessThanOrEqualTo = new SearchFilter.IsLessThanOrEqualTo(
                MailFolderObjectSchema.TotalItemCount,
                5);

            SearchFilter greaterThan = new SearchFilter.IsGreaterThan(
                MessageObjectSchema.CreatedDateTime,
                new DateTimeOffset(new DateTime(2019, 2, 1)));

            SearchFilter notEqualTo = new SearchFilter.NotEqualTo(
                MessageObjectSchema.Body,
                "test body");

            SearchFilter.SearchFilterCollection searchFilterCollection = new SearchFilter.SearchFilterCollection(
                FilterOperator.and,
                lessThanOrEqualTo,
                greaterThan,
                notEqualTo);

            Assert.AreEqual(
                FilterOperator.and,
                searchFilterCollection.FilterOperator);

            Assert.AreEqual(
                "$filter=TotalItemCount le 5 and CreatedDateTime gt 2019-02-01T12:00:00Z and Body ne 'test body'",
                searchFilterCollection.Query);

            Assert.ThrowsException <ArgumentException>(() =>
            {
                searchFilterCollection = new SearchFilter.SearchFilterCollection(FilterOperator.ge);
            });

            searchFilterCollection = new SearchFilter.SearchFilterCollection(
                FilterOperator.or,
                lessThanOrEqualTo,
                greaterThan,
                notEqualTo);

            Assert.AreEqual(
                FilterOperator.or,
                searchFilterCollection.FilterOperator);

            Assert.AreEqual(
                "$filter=TotalItemCount le 5 or CreatedDateTime gt 2019-02-01T12:00:00Z or Body ne 'test body'",
                searchFilterCollection.Query);
        }
示例#4
0
        /// <summary>
        /// Find all folders under MsgRootFolder
        /// </summary>
        /// <param name="service"></param>
        /// <returns>Result of a folder search operation</returns>
        public static List <Folder> Folders(ExchangeService service, FolderId SearchRootFolder)
        {
            // try to find all folder that are unter MsgRootFolder
            int  pageSize      = 100;
            int  pageOffset    = 0;
            bool moreItems     = true;
            var  view          = new FolderView(pageSize, pageOffset);
            var  resultFolders = new List <Folder>();

            view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
            view.PropertySet.Add(FolderSchema.DisplayName);

            // we define the seacht filter here. Find all folders which hold more than 0 elements
            SearchFilter searchFilter = new SearchFilter.IsGreaterThan(FolderSchema.TotalCount, 0);

            view.Traversal = FolderTraversal.Deep;

            while (moreItems)
            {
                try
                {
                    findFolders = service.FindFolders(SearchRootFolder, searchFilter, view);

                    moreItems = findFolders.MoreAvailable;

                    foreach (var folder in findFolders)
                    {
                        resultFolders.Add(folder);
                    }
                    // if more folders than the offset is aviable we need to page
                    if (moreItems)
                    {
                        view.Offset += pageSize;
                    }
                }
                catch (Exception ex)
                {
                    log.Error("Failed to fetch folders.", ex);
                    moreItems = false;
                    Environment.Exit(3);
                }
            }
            return(resultFolders);
        }
示例#5
0
        static void GetFoldersPermissions(string utente)
        {
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);

            service.Credentials = new NetworkCredential(username, password);
            //    service.AutodiscoverUrl(user1Email);
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;


            service.Url = new Uri(WebServicesURL);
            // Create a property set to use for folder binding.
            PropertySet propSet = new PropertySet(BasePropertySet.IdOnly, FolderSchema.Permissions);

            var mailbox = new Mailbox(utente);


            FolderView view = new FolderView(10);

            view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
            view.PropertySet.Add(FolderSchema.DisplayName);
            SearchFilter searchFilter = new SearchFilter.IsGreaterThan(FolderSchema.TotalCount, 0);

            view.Traversal = FolderTraversal.Deep;


            FindFoldersResults findFolderResults = service.FindFolders(WellKnownFolderName.Root, searchFilter, view);


            foreach (Folder folderSearch in findFolderResults)
            {
                try
                {
                    Console.WriteLine(folderSearch.DisplayName);

                    GetFolderPermissions(utente, folderSearch.DisplayName.ToLower());
                }
                catch (Exception e) { Trace.WriteLine(DateTime.Now.ToString("yyyyMMddHHmmss") + "::ERR::FolderPermissions::FAILED::Cannot bind to mailbox " + utente + " --> " + e.Message); }
            }
        }
        public EmailMessage GetVpnEmail(ExchangeService client, string emailSubjectPrefix, string inboxSubFolderNameWithVpnEmails = null)
        {
            Folder vpnFolder = GetVpnFolder(client, inboxSubFolderNameWithVpnEmails);

            // Searching emails into a specific folder:
            // FindItemsResults<Item> emailsInVpnFolder = client.FindItems("MyEmailFolder", subjectFilter, folderView); // This throws an exception, the folder ID is not the folder name but some kind of GUID, throws exception.

            // https://docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-use-search-filters-with-ews-in-exchange
            var subjectFilterBySubject = new SearchFilter.ContainsSubstring(ItemSchema.Subject, $"{emailSubjectPrefix}", ContainmentMode.Substring, ComparisonMode.IgnoreCase);
            var searchFilterUnread     = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
            var searchFilterRecentDate = new SearchFilter.IsGreaterThan(EmailMessageSchema.DateTimeReceived, DateTime.UtcNow.AddMinutes(-30));
            var searchFilterNewVpnCode = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterUnread, subjectFilterBySubject, searchFilterRecentDate);
            var emailView = new ItemView(pageSize: 5);
            var vpnEmails = vpnFolder.FindItems(searchFilterNewVpnCode, emailView).OrderByDescending(e => e.DateTimeSent);
            var mostRecentVpnEmailItem = vpnEmails.FirstOrDefault();

            if (mostRecentVpnEmailItem?.Id == null)
            {
                return(null);
            }
            var mostRecentVpnEmailMessage = EmailMessage.Bind(client, mostRecentVpnEmailItem.Id);

            return(mostRecentVpnEmailMessage);
        }
示例#7
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);
            }
        }
示例#8
0
        public bool SetConversation(ref string kom)
        {
            try
            {
                string     folderToSync = string.Empty;
                string     days         = string.Empty;
                FolderView view         = new FolderView(100);
                view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
                view.PropertySet.Add(FolderSchema.DisplayName);
                view.Traversal = FolderTraversal.Deep;
                if (service != null)
                {
                    List <string> lstDirsToChoose  = new List <string>();
                    List <string> lstDirsToDisplay = new List <string>();
                    //find specific folder

                    lstDirsToChoose.Add(WellKnownFolderName.Inbox.ToString());
                    lstDirsToChoose.Add(WellKnownFolderName.SentItems.ToString());
                    lstDirsToDisplay.Add(WellKnownFolderName.Inbox.ToString());
                    lstDirsToDisplay.Add(WellKnownFolderName.SentItems.ToString());

                    FolderDecision fd = new FolderDecision(lstDirsToDisplay, true);
                    fd.SelectedFolder = lstDirsToChoose.FirstOrDefault();
                    fd.ShowDialog();

                    if (!Directory.Exists(mailDir + "\\" + fd.SelectedFolder.Replace(" ", "")))
                    {
                        Directory.CreateDirectory(mailDir + "\\" + fd.SelectedFolder.Replace(" ", ""));
                    }
                    mailDir      = mailDir + "\\" + fd.SelectedFolder.Replace(" ", "");
                    folderToSync = lstDirsToChoose.Where(q => q == fd.SelectedFolder).FirstOrDefault();
                    days         = fd.SelectedTime;

                    SearchFilter sfs = new SearchFilter.IsGreaterThan(ItemSchema.DateTimeReceived, DateTime.Now.AddDays(-int.Parse(days)));

                    int      offset   = 0;
                    int      pageSize = 50;
                    bool     more     = true;
                    ItemView viewItem = new ItemView(pageSize, offset, OffsetBasePoint.Beginning);

                    FindItemsResults <Item> findResults;
                    List <EmailMessage>     emails = new List <EmailMessage>();

                    while (more)
                    {
                        WellKnownFolderName folderName = WellKnownFolderName.Inbox;
                        if (folderToSync == WellKnownFolderName.Inbox.ToString())
                        {
                            folderName = WellKnownFolderName.Inbox;
                        }
                        if (folderToSync == WellKnownFolderName.SentItems.ToString())
                        {
                            folderName = WellKnownFolderName.SentItems;
                        }

                        findResults = service.FindItems(folderName, sfs, viewItem);
                        foreach (var item in findResults.Items)
                        {
                            emails.Add((EmailMessage)item);
                        }

                        more = findResults.MoreAvailable;
                        if (more)
                        {
                            viewItem.Offset += pageSize;
                        }
                    }
                    PropertySet properties = (BasePropertySet.FirstClassProperties); //A PropertySet with the explicit properties you want goes here
                    service.LoadPropertiesForItems(emails, properties);
                    int index = 1;
                    foreach (EmailMessage em in emails)
                    {
                        em.Load(new PropertySet(ItemSchema.MimeContent));
                        MimeContent mc    = em.MimeContent;
                        string      nazwa = BitConverter.ToString(MD5.Create().ComputeHash(ASCIIEncoding.ASCII.GetBytes(em.Id.UniqueId)));
                        if (!File.Exists(mailDir + "\\" + nazwa + ".eml"))
                        {
                            File.WriteAllBytes(mailDir + "\\" + nazwa + ".eml", em.MimeContent.Content);
                            OnNewFilesNumberEvent(string.Format("{0} {1}", index, _rm.GetString("strNewEmailsInsideOutlookDirRes")));
                            index++;
                        }
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                kom = _rm.GetString("lblTotalGenericErrorRes") + " " + ex.Message;
                return(false);
            }
        }
        public void ExChangeMail()
        {
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);

            service.Credentials = new WebCredentials(UserName, Password);
            //给出Exchange Server的URL
            service.Url = new Uri(ServerUrl);
            //你自己的邮件地址 [email protected]
            service.AutodiscoverUrl(Email, RedirectionCallback);
            //已读条件
            SearchFilter isRead = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true);
            //日期条件
            SearchFilter timeLimit        = new SearchFilter.IsGreaterThan(EmailMessageSchema.DateTimeSent, Convert.ToDateTime("2019/9/26 00:00"));
            SearchFilter timeLimitMaxTime = new SearchFilter.IsLessThan(EmailMessageSchema.DateTimeSent, Convert.ToDateTime("2019/10/25 23:59"));

            //复合条件
            SearchFilter.SearchFilterCollection searchlist = new SearchFilter.SearchFilterCollection(LogicalOperator.And, isRead, timeLimit, timeLimitMaxTime);
            //查找Inbox,加入过滤器条件,结果10条
            var IV = new ItemView(int.MaxValue);


            //MsgFolderRoot 所有邮件文件夹 ! 从所有文件夹中 找到 test文件夹
            //FolderId folder = FindFolderIdByDisplayName(service, "test", WellKnownFolderName.MsgFolderRoot);
            //DeletedItems:已删除邮件   InBox:收件箱
            //FindItemsResults<Item> findResults = service.FindItems(folder, sf, IV);

            FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.DeletedItems, searchlist, IV);
            PropertySet             props       = new PropertySet(BasePropertySet.IdOnly);

            props.Add(ItemSchema.Subject);
            props.Add(ItemSchema.Body);

            List <NewTempModel> list = new List <NewTempModel>();

            if (findResults != null && findResults.Items != null && findResults.Items.Count > 0)
            {
                var i = 1;

                foreach (Item item in findResults.Items)
                {
                    var total = findResults.Items.Count();

                    EmailMessage email = EmailMessage.Bind(service, item.Id);
                    props.RequestedBodyType = BodyType.Text;
                    EmailMessage emailNoHtml = EmailMessage.Bind(service, item.Id, props);
                    string       emailText   = emailNoHtml.Body.Text;



                    //TempleModel tm = new TempleModel();
                    //tm.UserName = email.Sender == null ? "" : email.Sender.Name;
                    //tm.Description = emailText;
                    //tm.UserDate = email.DateTimeSent.ToShortDateString();
                    //tm.FixDate = tm.UserDate;
                    //tm.ComfiDate = tm.FixDate;
                    //tm.Month = $"{email.DateTimeSent.Year}/{email.DateTimeSent.Month}";
                    //tm = SwithCategory(tm);

                    NewTempModel tm = new NewTempModel();
                    tm.Requestor_Email   = email.Sender == null ? "" : email.Sender.Address;
                    tm.Request_Date_Time = email.DateTimeCreated.ToString();
                    tm.Issue_Description = emailText;
                    tm.Closure_Date_Time = email.LastModifiedTime.ToString();
                    tm.Application       = "F3";
                    tm.Severity_Level    = "P1";
                    tm.Feedback_Source   = "邮箱";
                    tm.Impacted_BU       = "F3";
                    tm.Category          = "资讯类";
                    tm.Sub_Category      = "后台处理";
                    tm.Caused_By         = "F3";
                    tm.Resolution_Detail = "后台处理数据";
                    tm.Description       = "转交任务";
                    tm.Status            = "Closed";
                    tm.Resolver          = "alvin";
                    tm.SLA_Meet          = "Yes";
                    //tm.Closure_Date_Time=email.to

                    if (tm != null)
                    {
                        list.Add(tm);
                        Console.WriteLine(emailText);
                        Console.WriteLine("-------------------------" + i + "/" + total + "down!--------------------------------");
                    }
                    //list.Add(tm);
                    i++;
                }
            }
            DataTable dt = ToDataTable(list);

            string path = @"C:\Users\Administrator\Desktop\wow1\1.xlsx";

            ExcelHelper.DataTableToExcel(path, dt, "Incident Pattern", false);
            Console.ReadKey();
        }
示例#10
0
        public static TreeNode GetFoldersTree()
        {
            TreeNode rootNode = new TreeNode();

            try
            {
                if (null == CreateService())
                {
                    MessageBox.Show("Unable to create Exchange Service Object");
                }


                if (m_UseImpersonation)
                {
                    rootNode.Text = "Root - " + m_EmailAddress;
                }
                else if (m_UseDefaultCredentials)
                {
                    rootNode.Text = "Root";
                }
                else
                {
                    rootNode.Text = "Root - " + m_Username;
                }
                rootNode.Tag = null;


                // Set the page size.
                int pageSize = 100;
                // Set the offset for the paged search.
                int offset = 0;



                // Set the flag that indicates whether to continue iterating through additional pages.
                bool MoreItems = true;

                // Continue paging while there are more items to page.
                while (MoreItems)
                {
                    // Create a view.
                    FolderView view = new FolderView(pageSize, offset, OffsetBasePoint.Beginning);

                    // Identify the properties to return in the results set.
                    view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
                    view.PropertySet.Add(FolderSchema.DisplayName);
                    view.PropertySet.Add(FolderSchema.ParentFolderId);

                    // Return only folders that contain items.
                    SearchFilter searchFilter = new SearchFilter.IsGreaterThan(FolderSchema.TotalCount, 0);

                    // Unlike FindItem searches, folder searches can be deep traversals.
                    view.Traversal = FolderTraversal.Deep;
                    FindFoldersResults findFolderResults;
                    if (m_UseImpersonation)
                    {
                        // Send the request to search the mailbox and get the results.
                        findFolderResults = m_ExchangeService.FindFolders(new FolderId(WellKnownFolderName.MsgFolderRoot, new Mailbox(m_EmailAddress)), searchFilter, view);
                    }
                    else
                    {
                        findFolderResults = m_ExchangeService.FindFolders(WellKnownFolderName.MsgFolderRoot, searchFilter, view);
                    }

                    // Process each item.
                    foreach (Folder myFolder in findFolderResults.Folders)
                    {
                        TreeNode parentNode = FromID(myFolder.ParentFolderId.UniqueId, rootNode);
                        TreeNode childNode  = parentNode.Nodes.Add(myFolder.DisplayName);
                        childNode.Tag = myFolder.Id.UniqueId;
                    }

                    // Determine whether there are more folders to return.
                    if (findFolderResults.MoreAvailable)
                    {
                        // Make recursive calls with offsets set for the FolderView to get the remaining folders in the result set.
                    }
                    // Set the flag to discontinue paging.
                    if (!findFolderResults.MoreAvailable)
                    {
                        MoreItems = false;
                    }

                    // Update the offset if there are more items to page.
                    if (MoreItems)
                    {
                        offset = findFolderResults.NextPageOffset.Value;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            return(rootNode);
        }
示例#11
0
        public void GetEmails()
        {
            try
            {
                string pass = string.Empty;
                string user = string.Empty;

                MailSync.Credentials cred = new MailSync.Credentials();
                cred.GetCredentials("Input authorization data", "username [email protected]", ref user, ref pass);

                string url = Interaction.InputBox("Address with https schema", "Exchange address", "https://");


                string mail = Interaction.InputBox("Input mailbox ([email protected])", "Enter mailbox", user);

                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
                service.Credentials  = new WebCredentials(user, pass);
                service.TraceEnabled = true;
                service.TraceFlags   = TraceFlags.All;
                service.Url          = new Uri(url);
                service.AutodiscoverUrl(mail, RedirectionUrlValidationCallback);

                SearchFilter sfs = new SearchFilter.IsGreaterThan(ItemSchema.DateTimeReceived, DateTime.Now.AddDays(-3));

                int      offset   = 0;
                int      pageSize = 50;
                bool     more     = true;
                ItemView view     = new ItemView(pageSize, offset, OffsetBasePoint.Beginning);

                FindItemsResults <Item> findResults;
                List <EmailMessage>     emails = new List <EmailMessage>();

                while (more)
                {
                    findResults = service.FindItems(WellKnownFolderName.Inbox, sfs, view);
                    foreach (var item in findResults.Items)
                    {
                        emails.Add((EmailMessage)item);
                    }

                    more = findResults.MoreAvailable;
                    if (more)
                    {
                        view.Offset += pageSize;
                    }
                }
                PropertySet properties = (BasePropertySet.FirstClassProperties); //A PropertySet with the explicit properties you want goes here
                service.LoadPropertiesForItems(emails, properties);

                foreach (EmailMessage em in emails)
                {
                    em.Load(new PropertySet(ItemSchema.MimeContent));
                    MimeContent mc    = em.MimeContent;
                    string      nazwa = Guid.NewGuid().ToString();

                    File.WriteAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Mailbox\\" + nazwa + ".eml", mc.Content);
                }


                Trace.WriteLine("TEST has ended");
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Error: " + ex.Message);
            }
        }
示例#12
0
        static int Main(string[] args)
        {
            // Test if input arguments were supplied:
            if (args.Length != 2)
            {
                Console.WriteLine("Please enter a config file");
                return(1);
            }
            string fileCfg = args[0];
            string fileLog = args[1];

            Logger(fileLog, "File cfg: " + fileCfg);
            Logger(fileLog, "File log: " + fileLog);

            try
            {
                StreamReader  file     = new StreamReader(@fileCfg);
                XmlSerializer reader   = new XmlSerializer(typeof(EWS_1C));
                EWS_1C        overview = (EWS_1C)reader.Deserialize(file);
                file.Close();

                ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                service.UseDefaultCredentials = false;
                service.Credentials           = new WebCredentials(overview.Login, overview.Password, overview.Domain);
                service.Url = new Uri(overview.url);

                //service.EnableSs
                Logger(fileLog, service.Url.ToString());

                service.TraceEnabled = false;
                service.TraceFlags   = TraceFlags.All;

                // emails
                Logger(fileLog, "Писем для отправки: " + overview.emails.Length);
                for (int i = 0; i < overview.emails.Length; i++)
                {
                    EmailOut eml = overview.emails[i];
                    //System.Console.WriteLine("- Subject: " + eml.Subject);

                    EmailMessage message = new EmailMessage(service);
                    message.Subject = eml.Subject;
                    message.Body    = eml.Body;
                    for (int j = 0; j < eml.Recipient.Length; j++)
                    {
                        message.ToRecipients.Add(eml.Recipient[j]);
                    }
                    for (int j = 0; j < eml.File.Length; j++)
                    {
                        if (!String.IsNullOrEmpty(eml.File[j]))
                        {
                            message.Attachments.AddFileAttachment(eml.File[j]);
                        }
                    }

                    message.SendAndSaveCopy();
                    Logger(fileLog, "Email № " + (i + 1) + " send recipient = " + eml.Recipient.ToString());
                }

                // 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));
                SearchFilter sf =
                    new SearchFilter.IsGreaterThan(ItemSchema.DateTimeReceived, DateTime.Now.AddDays(-5));

                ItemView view = new ItemView(30); //Больше 30 писем не получать

                // 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);

                //var emailProps = new PropertySet(ItemSchema.MimeContent, ItemSchema.Body,
                //    ItemSchema.InternetMessageHeaders);

                var dirOut = Path.GetDirectoryName(fileCfg);
                Logger(fileLog, "dirOut = " + dirOut);

                List <EmailIn> list = new List <EmailIn>();

                Logger(fileLog, "Писем получено: " + findResults.TotalCount.ToString());
                foreach (EmailMessage i in findResults)
                {
                    //var email_ews = EmailMessage.Bind(service, i.Id, emailProps);
                    i.Load();
                    if (!i.IsRead)
                    {
                        i.IsRead = true;
                        i.Update(ConflictResolutionMode.AutoResolve);
                    }

                    var eml = new EmailIn();
                    eml.IdObj   = Guid.NewGuid().ToString();
                    eml.Subject = i.Subject;
                    eml.Body    = i.Body;
                    List <String> listRecipients = new List <String>();
                    foreach (EmailAddress ToRecipient in i.ToRecipients)
                    {
                        listRecipients.Add(ToRecipient.Name + " <" + ToRecipient.Address + ">");
                    }
                    eml.Recipient = listRecipients.ToArray();
                    eml.From      = i.From.Name + " <" + i.From.Address + ">";
                    eml.Id        = i.InternetMessageId;
                    eml.DateSend  = i.DateTimeSent;
                    Logger(fileLog, "id email: " + eml.Id);
                    Logger(fileLog, "id: " + eml.IdObj);


                    if (i.HasAttachments)
                    {
                        string dirEmail = Path.Combine(dirOut, "files", eml.IdObj);
                        if (!Directory.Exists(dirEmail))
                        {
                            Directory.CreateDirectory(dirEmail);
                        }
                        List <String> listFiles = new List <String>();
                        foreach (Attachment attachment in i.Attachments)
                        {
                            if (attachment is FileAttachment)
                            {
                                FileAttachment fileAttachment = attachment as FileAttachment;
                                string         fileEmail      = Path.Combine(dirEmail, fileAttachment.Name);
                                fileAttachment.Load(fileEmail);
                                listFiles.Add(fileEmail);
                            }
                            else
                            {
                                //Вложенные письма нам не нужны
                                //ItemAttachment itemAttachment = attachment as ItemAttachment;
                                //itemAttachment.Load();
                            }
                        }

                        eml.File = listFiles.ToArray();
                    }

                    list.Add(eml);
                }

                var outData = new Messages();
                outData.emails = list.ToArray();

                var writer = new System.Xml.Serialization.XmlSerializer(typeof(Messages));
                var wfile  = new System.IO.StreamWriter(@dirOut + "\\messages.xml");
                writer.Serialize(wfile, outData);
                wfile.Close();


                Logger(fileLog, "Done!");
            }
            catch (Exception e)
            {
                Logger(fileLog, e.Message);
            }

            return(0);
        }