Ejemplo n.º 1
1
        public void CheckMail()
        {
            try
            {
                string processLoc = dataActionsObject.getProcessingFolderLocation();
                StreamWriter st = new StreamWriter("C:\\Test\\_testings.txt");
                string emailId = "*****@*****.**";// ConfigurationManager.AppSettings["UserName"].ToString();
                if (emailId != string.Empty)
                {
                    st.WriteLine(DateTime.Now + " " + emailId);
                    st.Close();
                    ExchangeService service = new ExchangeService();
                    service.Credentials = new WebCredentials(emailId, "Sea2013");
                    service.UseDefaultCredentials = false;
                    service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
                    Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
                    SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
                    if (inbox.UnreadCount > 0)
                    {
                        ItemView view = new ItemView(inbox.UnreadCount);
                        FindItemsResults<Item> findResults = inbox.FindItems(sf, view);
                        PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.From, EmailMessageSchema.ToRecipients);
                        itempropertyset.RequestedBodyType = BodyType.Text;
                        //inbox.UnreadCount
                        ServiceResponseCollection<GetItemResponse> items = service.BindToItems(findResults.Select(item => item.Id), itempropertyset);
                        MailItem[] msit = getMailItem(items, service);

                        foreach (MailItem item in msit)
                        {
                            item.message.IsRead = true;
                            item.message.Update(ConflictResolutionMode.AlwaysOverwrite);
                            foreach (Attachment attachment in item.attachment)
                            {
                                if (attachment is FileAttachment)
                                {
                                    string extName = attachment.Name.Substring(attachment.Name.LastIndexOf('.'));
                                    FileAttachment fileAttachment = attachment as FileAttachment;
                                    FileStream theStream = new FileStream(processLoc + fileAttachment.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                                    fileAttachment.Load(theStream);
                                    byte[] fileContents;
                                    MemoryStream memStream = new MemoryStream();
                                    theStream.CopyTo(memStream);
                                    fileContents = memStream.GetBuffer();
                                    theStream.Close();
                                    theStream.Dispose();
                                    Console.WriteLine("Attachment name: " + fileAttachment.Name + fileAttachment.Content + fileAttachment.ContentType + fileAttachment.Size);
                                }
                            }
                        }
                    }
                    DeleteMail(emailId);
                }
            }
            catch (Exception ex)
            {

            }
        }
Ejemplo n.º 2
0
        public bool FetchMeetingRequestbyUniqueId(string uniqueId, out MeetingRequest mr)
        {
            bool result = false;

            mr = null;

            try
            {
                SearchFilter.SearchFilterCollection searchFilter = new SearchFilter.SearchFilterCollection();
                searchFilter.Add(new SearchFilter.ContainsSubstring(MeetingRequestSchema.Subject, uniqueId));
                ItemView view = new ItemView(500);
                //view.PropertySet = new PropertySet(BasePropertySet.IdOnly, MeetingRequestSchema.Subject, MeetingRequestSchema.Start);
                FindItemsResults <Item> findResults = _service.FindItems(WellKnownFolderName.Inbox, searchFilter, view);

                if (findResults.Items.Count > 0)
                {
                    mr = findResults.Items[0] as MeetingRequest;
                    //mr.Load();
                    result = true;
                }
            }
            catch (Exception ex)
            {
                string msg = String.Format("FetchMeetingRequestbyUniqueId\n{0}\n{1}", ex.Message, ex.StackTrace);
                System.Diagnostics.EventLog.WriteEntry("ExchangeWebServices", msg, System.Diagnostics.EventLogEntryType.Error);
            }


            return(result);
        }
Ejemplo n.º 3
0
        public bool FetchAppointmentbyUniqueId(string uniqueId, out Appointment appt, int occurrance = 1)
        {
            bool result = false;

            appt = null;

            try
            {
                SearchFilter.SearchFilterCollection searchFilter = new SearchFilter.SearchFilterCollection();
                searchFilter.Add(new SearchFilter.ContainsSubstring(AppointmentSchema.Subject, uniqueId));
                ItemView view = new ItemView(500);
                view.PropertySet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.AppointmentType);
                FindItemsResults <Item> findResults = _service.FindItems(WellKnownFolderName.Calendar, searchFilter, view);

                if (findResults.Items.Count > 0)
                {
                    int index = occurrance - 1;
                    if (findResults.Items[index] == null)
                    {
                        index = 0;
                    }
                    appt = findResults.Items[index] as Appointment;
                    appt.Load();
                    result = true;
                }
            }
            catch (Exception ex)
            {
                string msg = String.Format("FetchAppintmentbyUniqueId\n{0}\n{1}", ex.Message, ex.StackTrace);
                System.Diagnostics.EventLog.WriteEntry("ExchangeWebServices", msg, System.Diagnostics.EventLogEntryType.Error);
            }

            return(result);
        }
Ejemplo 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;
     }
 }
Ejemplo n.º 5
0
        public ExchangeSecretar(string _exchangeServiceAddress, string _targetEmailBoxAddress, string _paswwordForThis, List <string> _keyWords)
        {
            exchangeServiceAddress = _exchangeServiceAddress;
            targetEmailBoxAddress  = _targetEmailBoxAddress;
            passwordForThis        = _paswwordForThis;
            keyWords = new List <string>();
            foreach (var item in _keyWords)
            {
                keyWords.Add(item);
            }
            exchangeService             = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
            exchangeService.Credentials = new WebCredentials(targetEmailBoxAddress, passwordForThis);
            exchangeService.AutodiscoverUrl(targetEmailBoxAddress, RedirectionUrlValidationCallback);
            itemIds = new Collection <ItemId>();
            Folder       folder       = Folder.Bind(exchangeService, WellKnownFolderName.Inbox);
            ItemView     view         = new ItemView(1);
            SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
            var          buffer       = folder.FindItems(searchFilter, view).ToList();

            if (buffer == null || buffer.Count == 0)
            {
                return;
            }
            foreach (var item in buffer)
            {
                itemIds.Add(item.Id);
            }
        }
Ejemplo n.º 6
0
        //gavdcodeend 13

        //gavdcodebegin 14
        private static void ExportOneAppointment(ExchangeService ExService)
        {
            SearchFilter myFilter = new SearchFilter.SearchFilterCollection(
                LogicalOperator.And,
                new SearchFilter.IsEqualTo(
                    AppointmentSchema.Subject,
                    "This is a new meeting"));
            ItemView myView = new ItemView(1);
            FindItemsResults <Item> findResults = ExService.FindItems(
                WellKnownFolderName.Calendar, myFilter, myView);

            ItemId myAppointmentId = null;

            foreach (Item oneItem in findResults)
            {
                myAppointmentId = oneItem.Id;
            }

            PropertySet myPropSet = new PropertySet(BasePropertySet.IdOnly,
                                                    AppointmentSchema.MimeContent);
            Appointment appointmentToExport = Appointment.Bind(ExService,
                                                               myAppointmentId, myPropSet);

            string apmFileName = @"C:\Temporary\myAppointment.ics";

            using (FileStream myStream = new FileStream(
                       apmFileName, FileMode.Create, FileAccess.Write))
            {
                myStream.Write(appointmentToExport.MimeContent.Content, 0,
                               appointmentToExport.MimeContent.Content.Length);
            }
        }
Ejemplo n.º 7
0
    public void SaveAttachment(string email, string password, string downloadfolder, string fromaddress)
    {
        ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);

        service.Credentials  = new WebCredentials(email, password);
        service.TraceEnabled = true;
        service.TraceFlags   = TraceFlags.All;
        service.AutodiscoverUrl(email, RedirectionUrlValidationCallback);
        // Bind the Inbox folder to the service object.
        Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
        // The search filter to get unread email.
        SearchFilter sf   = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
        ItemView     view = new ItemView(1);
        // Fire the query for the unread items.
        // This method call results in a FindItem call to EWS.
        FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view);

        foreach (EmailMessage item in findResults)
        {
            item.Load();
            /* download attachment if any */
            if (item.HasAttachments && item.Attachments[0] is FileAttachment && item.From.Address == fromaddress)
            {
                FileAttachment fileAttachment = item.Attachments[0] as FileAttachment;
                /* download attachment to folder */
                fileAttachment.Load(downloadfolder + fileAttachment.Name);
            }
            /* mark email as read */
            item.IsRead = true;
            item.Update(ConflictResolutionMode.AlwaysOverwrite);
        }
    }
        /// <summary>
        /// Build search filter from options.
        /// </summary>
        /// <param name="options">Options.</param>
        /// <returns>Search filter collection.</returns>
        private static SearchFilter.SearchFilterCollection BuildFilterCollection(ExchangeOptions options)
        {
            // Create search filter collection.
            var searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And);

            // Construct rest of search filter based on options
            if (options.GetOnlyEmailsWithAttachments)
            {
                searchFilter.Add(new SearchFilter.IsEqualTo(ItemSchema.HasAttachments, true));
            }

            if (options.GetOnlyUnreadEmails)
            {
                searchFilter.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
            }

            if (!string.IsNullOrEmpty(options.EmailSenderFilter))
            {
                searchFilter.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.Sender, options.EmailSenderFilter));
            }

            if (!string.IsNullOrEmpty(options.EmailSubjectFilter))
            {
                searchFilter.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, options.EmailSubjectFilter));
            }

            return(searchFilter);
        }
        /// <summary>
        /// Fecthing mails from a folder of mailbox.
        /// It will fetch without any filter
        /// </summary>
        /// <param name="service"></param>
        /// <param name="FolderName"></param>
        /// <param name="numberOfMails"></param>
        /// <param name="mailboxName"></param>
        /// <param name="onlyUnreadMails"></param>
        /// <returns></returns>
        static System.Collections.ObjectModel.Collection <Item> ReadMailFromFolder(ExchangeService service, String FolderName, Int32 numberOfMails, String mailboxName, bool onlyUnreadMails)
        {
            FolderView view = new FolderView(10000);

            view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
            view.PropertySet.Add(FolderSchema.DisplayName);
            view.Traversal = FolderTraversal.Deep;
            Mailbox            mailbox           = new Mailbox(mailboxName);
            FindFoldersResults findFolderResults = service.FindFolders(new FolderId(WellKnownFolderName.MsgFolderRoot, mailbox), view);

            foreach (Folder folder in findFolderResults)
            {
                //For Folder filter
                if (folder.DisplayName == FolderName)
                {
                    ItemView itemView = new ItemView(numberOfMails);
                    if (onlyUnreadMails)
                    {
                        SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
                        return((service.FindItems(folder.Id, searchFilter, itemView)).Items);
                    }
                    else
                    {
                        return((service.FindItems(folder.Id, itemView)).Items);
                    }
                }
            }
            throw new Exception("Folder is not found");
        }
Ejemplo n.º 10
0
        private static void SearchMailbox(string subject)
        {
            //Search filter
            SearchFilter            searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, subject));
            FindItemsResults <Item> findResults  = _service.FindItems(new FolderId(WellKnownFolderName.Inbox, ExchangeServiceConfig.Username), searchFilter, _view);

            if (!findResults.Items.Any())
            {
                Console.WriteLine("No messages found!");
                return;
            }

            var emails = new List <EmailMessage>();

            foreach (var item in findResults.Items)
            {
                emails.Add((EmailMessage)item);
            }

            var properties = (BasePropertySet.FirstClassProperties);

            _service.LoadPropertiesForItems(emails, properties);

            //Each email found
            foreach (var email in emails)
            {
                Console.WriteLine("Subject: " + email.Subject + " (de " + email.DateTimeReceived.ToString("dd/MM/yyyy HH:mm:ss") + ")");

                DownloadAttachments(email);
                ExportEmail(email);
            }
        }
Ejemplo n.º 11
0
        //gavdcodeend 04

        //gavdcodebegin 05
        static void FindRecurrentAppointmentsByDate(ExchangeService ExService)
        {
            SearchFilter.SearchFilterCollection myFilter =
                new SearchFilter.SearchFilterCollection
            {
                new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start,
                                                        DateTime.Now)
            };

            ItemView myView = new ItemView(100)
            {
                PropertySet = new PropertySet(BasePropertySet.IdOnly,
                                              AppointmentSchema.Subject,
                                              AppointmentSchema.Start,
                                              AppointmentSchema.Duration,
                                              AppointmentSchema.AppointmentType)
            };

            FindItemsResults <Item> foundResults = ExService.FindItems(
                WellKnownFolderName.Calendar, myFilter, myView);

            foreach (Item oneItem in foundResults.Items)
            {
                Appointment oneAppointment = oneItem as Appointment;
                if (oneAppointment.AppointmentType == AppointmentType.RecurringMaster)
                {
                    Console.WriteLine("Subject: " + oneAppointment.Subject);
                    Console.WriteLine("Start: " + oneAppointment.Start);
                    Console.WriteLine("Duration: " + oneAppointment.Duration);
                }
            }
        }
Ejemplo n.º 12
0
        //gavdcodeend 05

        //gavdcodebegin 06
        static void FindAppointmentsBySubject(ExchangeService ExService)
        {
            SearchFilter myFilter = new SearchFilter.SearchFilterCollection(
                LogicalOperator.And,
                new SearchFilter.IsEqualTo(
                    AppointmentSchema.Subject,
                    "This is a new meeting"));
            ItemView myView = new ItemView(1);
            FindItemsResults <Item> findResults = ExService.FindItems(
                WellKnownFolderName.Calendar, myFilter, myView);

            ItemId myAppointmentId = null;

            foreach (Item oneItem in findResults)
            {
                myAppointmentId = oneItem.Id;
            }

            PropertySet myPropSet = new PropertySet(BasePropertySet.IdOnly,
                                                    AppointmentSchema.Subject, AppointmentSchema.Location);
            Appointment myAppointment = Appointment.Bind(ExService,
                                                         myAppointmentId, myPropSet);

            Console.WriteLine(myAppointment.Subject + " - " + myAppointment.Location);
        }
Ejemplo n.º 13
0
        //gavdcodeend 05

        //gavdcodebegin 06
        static void ForwardEmail(ExchangeService ExService)
        {
            SearchFilter myFilter = new SearchFilter.SearchFilterCollection(
                LogicalOperator.And,
                new SearchFilter.IsEqualTo(
                    EmailMessageSchema.Subject,
                    "Email to forward"));
            ItemView myView = new ItemView(1);
            FindItemsResults <Item> findResults = ExService.FindItems(
                WellKnownFolderName.Inbox, myFilter, myView);

            ItemId myEmailId = null;

            foreach (Item oneItem in findResults)
            {
                myEmailId = oneItem.Id;
            }

            EmailMessage emailToReply = EmailMessage.Bind(ExService, myEmailId);

            EmailAddress[] forwardAddresses = new EmailAddress[1];
            forwardAddresses[0] = new EmailAddress("*****@*****.**");
            string myForward = "Forward body";

            emailToReply.Forward(myForward, forwardAddresses);
        }
Ejemplo n.º 14
0
        //gavdcodeend 06

        //gavdcodebegin 07
        static void UpdateOneAppointment(ExchangeService ExService)
        {
            SearchFilter myFilter = new SearchFilter.SearchFilterCollection(
                LogicalOperator.And,
                new SearchFilter.IsEqualTo(
                    AppointmentSchema.Subject,
                    "This is a new meeting"));
            ItemView myView = new ItemView(1);
            FindItemsResults <Item> findResults = ExService.FindItems(
                WellKnownFolderName.Calendar, myFilter, myView);

            ItemId myAppointmentId = null;

            foreach (Item oneItem in findResults)
            {
                myAppointmentId = oneItem.Id;
            }

            PropertySet myPropSet = new PropertySet(BasePropertySet.IdOnly,
                                                    AppointmentSchema.Subject, AppointmentSchema.Location);
            Appointment myAppointment = Appointment.Bind(ExService,
                                                         myAppointmentId, myPropSet);

            myAppointment.Location = "Other place";
            myAppointment.RequiredAttendees.Add("*****@*****.**");

            myAppointment.Update(ConflictResolutionMode.AlwaysOverwrite,
                                 SendInvitationsOrCancellationsMode.SendToAllAndSaveCopy);
        }
        /// <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);
        }
Ejemplo n.º 16
0
        public IEnumerable <Item> Get()
        {
            // Get the "Conversation History" folder, if not already found.
            if (_imHistoryFolder == null)
            {
                _imHistoryFolder = this.FindImHistoryFolder();
                if (_imHistoryFolder == null)
                {
                    throw new Exception("Could not find history folder");
                }
            }

            // Get Conversation History items.
            List <Item>             imHistoryItems = new List <Item>();
            FindItemsResults <Item> findResults;

            ItemView itemView = new ItemView(_pageSize);

            itemView.PropertySet = new PropertySet(BasePropertySet.IdOnly);
            SearchFilter.SearchFilterCollection searchFilterCollection = null;

            do
            {
                findResults = _exchangeService.FindItems(_imHistoryFolder.Id, searchFilterCollection, itemView);
                imHistoryItems.AddRange(findResults);
                itemView.Offset += _pageSize;
            } while (findResults.MoreAvailable);

            foreach (var item in imHistoryItems)
            {
                yield return(item);
            }
        }
Ejemplo n.º 17
0
        public void CleanEmail()
        {
            Logger.Debug(new LogInfo(MethodBase.GetCurrentMethod(), "DEB", "Svuoto la caselal di posta"));

            //cerco tutte le mail già lette
            SearchFilter sf = new SearchFilter.SearchFilterCollection(
                LogicalOperator.And,
                new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true) /*,
                                                                             * new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, "jarvis", ContainmentMode.Prefixed, ComparisonMode.IgnoreCase
                                                                             *
                                                                             * )*/);

            ItemView view = new ItemView(20);

            // Lanciamo la query
            FindItemsResults <Item> findResults = this.service.FindItems(WellKnownFolderName.Inbox, sf, view);

            Logger.Debug(new LogInfo(MethodBase.GetCurrentMethod(), "DEB", string.Format("Trovate {0} nuove mail da cancellare", findResults.TotalCount)));

            if (findResults.TotalCount > 0)
            {
                foreach (var itm in findResults)
                {
                    itm.Delete(DeleteMode.HardDelete);
                }
            }
        }
Ejemplo n.º 18
0
        private void GetExchangeItems(ExchangeService service)
        {
            int          unreadEmailCount = 0;
            SearchFilter searchFilter     = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
            //itemView upperbound value hardcoded because we need to do selective search on unread emails.
            ItemView view = new ItemView(999);
            FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, view);

            unreadEmailCount = findResults.Items.Count;
            if (findResults.Items.Count > 0)
            {
                service.LoadPropertiesForItems(findResults.Items, PropertySet.FirstClassProperties);
                //string Script = "";
                string Script = DBObj.GetCreationScript();
                //FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
                foreach (Item item in findResults.Items)
                {
                    string EmailProcessedMessage = ProcessExchangeItems(item, Script);
                    //Send email only in case we have something to return back to user.
                    if (!string.IsNullOrEmpty(EmailProcessedMessage))
                    {
                        EmailObj.SendEmail(service, item.Subject, EmailProcessedMessage, item);
                    }
                }
            }
        }
Ejemplo n.º 19
0
        private static void FindItems(ExchangeService service)
        {
            // Create a search collection that contains your search conditions.
            List <SearchFilter> searchFilterCollection = new List <SearchFilter>();

            searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, "Contoso"));
            searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Body, "Marketing"));

            // Create the search filter with a logical operator and your search parameters.
            SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray());

            // Limit the view to 50 items.
            ItemView view = new ItemView(50);

            // Limit the property set to the property ID for the base property set, and the subject and item class for the additional properties to retrieve.
            view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.ItemClass);

            // Setting the traversal to shallow will return all non-soft-deleted items in the specified folder.
            view.Traversal = ItemTraversal.Shallow;

            // Send the request to search the Inbox and get the results.
            FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, view);

            // Display each item.
            Console.WriteLine("\n" + "Item type".PadRight(50) + "\t" + "Subject");
            foreach (Item myItem in findResults.Items)
            {
                Console.WriteLine(myItem.GetType().ToString().PadRight(50) + "\t" + myItem.Subject.ToString());
            }
        }
Ejemplo n.º 20
0
        public IList <EmailMessageWrapper> FindUnreadEmails(ExchangeConfigurationCredentials credentials)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }

            var itemView = new ItemView(MaxItemCount);

            itemView.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);

            var outOffOfficeEmailFilter = new SearchFilter.IsNotEqualTo(ItemSchema.ItemClass, "IPM.Note.Rules.OofTemplate.Microsoft");
            var filters = new SearchFilter.SearchFilterCollection(LogicalOperator.And)
            {
                UnreadEmailFilter,
                outOffOfficeEmailFilter
            };
            var folderId = GetInboxFolder(credentials);

            var result = _exchangeService.FindItems(credentials, folderId, filters, itemView)
                         .Select(message => GetEmailMessageWrapper(message, credentials.Id))
                         .ToList();

            if (result.Any(c => c.Address == null || c.DisplayName == null || c.ExchangeConfigurationId == null || c.EmlContent == null || c.ItemId == null))
            {
                System.Diagnostics.Debug.WriteLine($"{result.Count} unread email(s) found in mailbox {credentials.ExchangeName}");
            }
            return(result);
        }
Ejemplo n.º 21
0
        private SearchFilter.SearchFilterCollection setupReadMailFilter()
        {
            SearchFilter.SearchFilterCollection EmailfilterCollection    = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
            SearchFilter.SearchFilterCollection readMailFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.Or);
            if (readMailFilter.HasValue)
            {
                switch (readMailFilter.Value)
                {
                case readMailFilterOptions.All:

                    readMailFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true));
                    readMailFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
                    break;

                case readMailFilterOptions.Unread:
                default:
                    readMailFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
                    break;

                case readMailFilterOptions.Read:
                    readMailFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true));
                    break;
                }
            }
            else
            {
                readMailFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
            }
            EmailfilterCollection.Add(readMailFilterCollection);
            return(EmailfilterCollection);
        }
Ejemplo n.º 22
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);
        }
Ejemplo n.º 23
0
        //gavdcodeend 08

        //gavdcodebegin 09
        static void AcceptDeclineOneAppointment(ExchangeService ExService)
        {
            SearchFilter myFilter = new SearchFilter.SearchFilterCollection(
                LogicalOperator.And,
                new SearchFilter.IsEqualTo(
                    AppointmentSchema.Subject,
                    "This is a new meeting"));
            ItemView myView = new ItemView(1);
            FindItemsResults <Item> findResults = ExService.FindItems(
                WellKnownFolderName.Calendar, myFilter, myView);

            ItemId myAppointmentId = null;

            foreach (Item oneItem in findResults)
            {
                myAppointmentId = oneItem.Id;
            }

            PropertySet myPropSet = new PropertySet(BasePropertySet.IdOnly,
                                                    AppointmentSchema.Subject, AppointmentSchema.Location);
            Appointment myAppointment = Appointment.Bind(ExService,
                                                         myAppointmentId, myPropSet);

            myAppointment.Accept(true);
            //myAppointment.AcceptTentatively(true);
            //myAppointment.Decline(true);

            AcceptMeetingInvitationMessage responseMessage =
                myAppointment.CreateAcceptMessage(true);

            responseMessage.Body        = new MessageBody("Meeting acknowledged");
            responseMessage.Sensitivity = Sensitivity.Private;
            responseMessage.Send();
        }
Ejemplo n.º 24
0
        public List <SearchResult> SearchFolder(FolderName folder, bool returnBody = true, bool returnAttachments = true)
        {
            var searchResult = new List <SearchResult>();

            var searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, SearchFilters.ToArray());

            var view = new ItemView(SearchLimit)
            {
                PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.HasAttachments, ItemSchema.DateTimeReceived)
            };

            view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
            view.Traversal = ItemTraversal.Shallow;

            var res = Service.FindItems((WellKnownFolderName)folder, searchFilter, view);

            if (res.TotalCount > 0)
            {
                foreach (var item in res.Items)
                {
                    if (item is EmailMessage)
                    {
                        searchResult.Add(new SearchResult {
                            UniqueId       = item.Id.UniqueId,
                            ReceivedOn     = item.DateTimeReceived,
                            Subject        = item.Subject,
                            HasAttachments = item.HasAttachments
                        });
                    }
                }
            }

            return(searchResult);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Get new unread email in inbox folder
        /// </summary>
        public void PullEmail()
        {
            try {
                DateTime from = DateTime.Now;
                if (DateTime.TryParse(ConfigurationManager.AppSettings["PullFrom"], out from))
                {
                    from = DateTime.Parse(ConfigurationManager.AppSettings["PullFrom"]);
                }

                ExchangeConnect();

                List <SearchFilter> filters = new List <SearchFilter>();
                filters.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
                filters.Add(new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.DateTimeCreated, from));

                SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, filters.ToArray());

                List <Item> findResults = _Emailservice.GetIndoxFormItem(searchFilter, new ItemView(int.MaxValue));
                _Logger.Info(string.Format("search item found = {0}", findResults.Count()));
                foreach (EmailMessage itemMessage in findResults)
                {
                    var item = _Emailservice.BindToEmailMessage(itemMessage.Id);
                    SaveEmail(item);
                }
            } catch (ServiceRequestException se) {
                _Logger.Error(se.Message, se);
                SendError(se);
            } catch (Exception ex) {
                _Logger.Error(ex.Message, ex);
                SendError(ex);
            }
        }
Ejemplo n.º 26
0
        //gavdcodeend 10

        //gavdcodebegin 11
        static void EntityExtractionFromEmail(ExchangeService ExService)
        {
            SearchFilter myFilter = new SearchFilter.SearchFilterCollection(
                LogicalOperator.And,
                new SearchFilter.IsEqualTo(
                    EmailMessageSchema.Subject,
                    "Entity extraction email"));
            ItemView myView = new ItemView(1);
            FindItemsResults <Item> findResults = ExService.FindItems(
                WellKnownFolderName.Inbox, myFilter, myView);

            ItemId myEmailId = null;

            foreach (Item oneItem in findResults)
            {
                myEmailId = oneItem.Id;
            }

            PropertySet myPropSet = new PropertySet(BasePropertySet.IdOnly,
                                                    ItemSchema.EntityExtractionResult);
            Item emailWithEntities =
                EmailMessage.Bind(ExService, myEmailId, myPropSet);

            if (emailWithEntities.EntityExtractionResult != null)
            {
                if (emailWithEntities.EntityExtractionResult.MeetingSuggestions != null)
                {
                    Console.WriteLine("Entity Meetings");
                    foreach (MeetingSuggestion oneMeeting in
                             emailWithEntities.EntityExtractionResult.MeetingSuggestions)
                    {
                        Console.WriteLine("Meeting: " + oneMeeting.MeetingString);
                    }
                    Console.WriteLine(Environment.NewLine);
                }

                if (emailWithEntities.EntityExtractionResult.EmailAddresses != null)
                {
                    Console.WriteLine("Entity Emails");
                    foreach (EmailAddressEntity oneEmail in
                             emailWithEntities.EntityExtractionResult.EmailAddresses)
                    {
                        Console.WriteLine("Email address: " + oneEmail.EmailAddress);
                    }
                    Console.WriteLine(Environment.NewLine);
                }

                if (emailWithEntities.EntityExtractionResult.PhoneNumbers != null)
                {
                    Console.WriteLine("Entity Phones");
                    foreach (PhoneEntity onePhone in
                             emailWithEntities.EntityExtractionResult.PhoneNumbers)
                    {
                        Console.WriteLine("Phone: " + onePhone.PhoneString);
                    }
                    Console.WriteLine(Environment.NewLine);
                }
            }
        }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            ExchangeService _exchangeService            = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
            string          _exchangeDomainUser         = ConfigurationManager.AppSettings["exchangeDomainUser"];
            string          _exchangeDomainUserPassword = ConfigurationManager.AppSettings["exchangeDomainUserPassword"];
            string          _exchangeUrl         = ConfigurationManager.AppSettings["exchangeUrl"];
            string          _exchangeMailSubject = ConfigurationManager.AppSettings["exchangeMailSubject"];

            try
            {
                _exchangeService = new ExchangeService
                {
                    Credentials = new WebCredentials(_exchangeDomainUser, _exchangeDomainUserPassword)
                };

                // This is the office365 webservice URL
                _exchangeService.Url = new Uri(_exchangeUrl);

                ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };

                // create archive folder
                FolderId folderId = CreateArchiveFolder(_exchangeService);

                // file download and move email to archive folder
                List <SearchFilter> searchFilterCollection = new List <SearchFilter>();
                searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, _exchangeMailSubject));
                SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray());
                ItemView     view         = new ItemView(50);
                view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived);
                view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
                view.Traversal = ItemTraversal.Shallow;
                FindItemsResults <Item> findResults = _exchangeService.FindItems(WellKnownFolderName.Inbox, searchFilter, view);

                if (findResults != null && findResults.Items != null && findResults.Items.Count > 0)
                {
                    foreach (EmailMessage item in findResults)
                    {
                        EmailMessage message = EmailMessage.Bind(_exchangeService, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments));
                        foreach (Attachment attachment in message.Attachments)
                        {
                            if (attachment is FileAttachment)
                            {
                                FileAttachment fileAttachment = attachment as FileAttachment;
                                fileAttachment.Load(@"D:\\Files\\" + fileAttachment.Name);
                            }
                        }

                        // move mail to archive folder
                        item.Move(folderId);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("new ExchangeService failed");
                return;
            }
        }
Ejemplo n.º 28
0
        public void ProcessMails()
        {
            // Get the inbox folder and load all properties. This results in a GetFolder call to EWS. 
            Folder folder = Folder.Bind(service, WellKnownFolderName.Inbox);
            PropertySet propSet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.Body, ItemSchema.TextBody, ItemSchema.NormalizedBody);
            //propSet.RequestedBodyType = BodyType.Text;
            //propSet.BasePropertySet = BasePropertySet.FirstClassProperties;
            ItemView view = new ItemView(1);
            SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
            var items = folder.FindItems(sf, view);

            foreach (var item in items)
            {
                Item mailItem = Item.Bind(service, item.Id, propSet);
                Console.WriteLine(mailItem.Subject);
                Console.WriteLine("*********************************************************");
                Console.WriteLine(mailItem.Body);
                Console.WriteLine("*********************************************************");
                Console.WriteLine(mailItem.TextBody ?? "");
                Console.WriteLine("*********************************************************");
                Console.WriteLine(mailItem.NormalizedBody ?? "");
                Console.WriteLine("*********************************************************");
                Console.WriteLine("\n\n\n\n\n\n\n\n\n\n\n");

                HtmlDocument htmlDoc = new HtmlDocument();
                htmlDoc.LoadHtml(mailItem.NormalizedBody);

                if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count() > 0)
                {
                    // TODO: Handle any parse errors as required
                }
                else
                {

                    if (htmlDoc.DocumentNode != null)
                    {
                        var nodes = htmlDoc.DocumentNode.SelectNodes("//table");
                        for (int i = 0; i < nodes.Count; i++)
                        {
                            var node = nodes[i];
                            if (i == 0)
                            {

                            }
                            else if (i == 1)
                            {
                                var table = Utilities.GetDataTable(node);
                            }
                            else
                            {
                                break; //TODO: raise error? continue silently?
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 29
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;
            }
        }
Ejemplo n.º 30
0
 private EmailMessage GetEmailWithId(string InternetMessageId)
 {
     if (!string.IsNullOrEmpty(InternetMessageId))
     {
         SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.InternetMessageId, InternetMessageId));
         return (EmailMessage)FindItemsCurrentFolder(sf, new ItemView(1)).FirstOrDefault() ?? null;
     }
     return null;
 }
Ejemplo n.º 31
0
        public void getMails(string folderName, string keyword)
        {
            SearchFilter            sf          = null;
            FindItemsResults <Item> findResults = null;

            if (!string.IsNullOrEmpty(keyword))
            {
                sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.ContainsSubstring(ItemSchema.Subject, keyword, ContainmentMode.Substring, ComparisonMode.IgnoreCase));
            }

            if (string.IsNullOrEmpty(folderName))
            {
                if (sf != null)
                {
                    sf          = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.ContainsSubstring(ItemSchema.Subject, keyword, ContainmentMode.Substring, ComparisonMode.IgnoreCase));
                    findResults = service.FindItems(WellKnownFolderName.Inbox, sf, new ItemView(10));
                }
                else
                {
                    findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
                }
            }
            else
            {
                if (treeViewFolder.SelectedNode == null)
                {
                    MessageBox.Show("Select a folder under Inbox firstly.");
                    return;
                }
                else
                {
                    FolderId folderId = new FolderId(folderName);
                    if (sf != null)
                    {
                        sf          = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.ContainsSubstring(ItemSchema.Subject, keyword, ContainmentMode.Substring, ComparisonMode.IgnoreCase));
                        findResults = service.FindItems(folderId, sf, new ItemView(10));
                    }
                    else
                    {
                        findResults = service.FindItems(folderId, new ItemView(10));
                    }
                }
            }

            this.listViewMail.View = View.Details;
            this.listViewMail.Items.Clear();

            foreach (Item item in findResults.Items)
            {
                EmailMessage em           = item as EmailMessage;
                var          listViewItem = new ListViewItem(new[] { em.Sender.Name, em.DisplayTo, item.Subject, item.DateTimeReceived.ToString(), em.Id.UniqueId, em.IsRead ? "Read" : "UnRead" });

                this.listViewMail.Items.Add(listViewItem);
            }

            this.txtLog.Text += "Get mail list success\r\nEWS API:FindItems\r\nLocation:..\\EWS\\EWS\\Form1.cs line(112, 116, 132, 136)\r\n\r\n";
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Search the Inbox for the first unread email with an attachment matching the specified regular expression, and if found, download the attachment to the specified directory.
        /// </summary>
        /// <param name="attachmentNamePattern">The attachment filename pattern to search for.</param>
        /// <param name="targetDirectory">The (writable) directory where a found attachment will be saved.</param>
        /// <returns>True if a matching attachment was found and downloaded. False otherwise.</returns>
        public virtual bool DownloadAttachment(Regex attachmentNamePattern, string targetDirectory)
        {
            //we don't know how many items we'll have to search (likely nowhere near int.MaxValue)
            ItemView view = new ItemView(int.MaxValue);

            //we want the most recently received item
            view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);

            //load the properties required to perform a search for the attachment
            view.PropertySet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.IsRead, EmailMessageSchema.HasAttachments);

            //build the search filter
            SearchFilter filter = new SearchFilter.SearchFilterCollection(
                LogicalOperator.And,
                new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false),
                new SearchFilter.IsEqualTo(EmailMessageSchema.HasAttachments, true)
                );

            //perform the search and return the results as EmailMessage objects
            var  results         = Inbox.FindItems(filter, view).Cast <EmailMessage>();
            bool foundAttachment = false;

            foreach (var result in results)
            {
                //another call to EWS to actually load in this email's attachment collection
                var email = EmailMessage.Bind(exchangeService, result.Id, new PropertySet(EmailMessageSchema.Attachments));

                foreach (var attachment in email.Attachments)
                {
                    if (attachmentNamePattern.IsMatch(attachment.Name))
                    {
                        FileAttachment fileAttachment = attachment as FileAttachment;
                        if (fileAttachment != null)
                        {
                            //save the attachment to the target directory
                            fileAttachment.Load(Path.Combine(targetDirectory, fileAttachment.Name));
                            //mark the email as read
                            email.IsRead = true;
                            email.Update(ConflictResolutionMode.AlwaysOverwrite);
                            //get outta here!
                            foundAttachment = true;
                            break;
                        }
                    }
                }

                if (foundAttachment)
                {
                    break;
                }
            }

            return(foundAttachment);
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Search the Inbox for the first unread email with an attachment matching the specified regular expression, and if found, download the attachment to the specified directory.
        /// </summary>
        /// <param name="attachmentNamePattern">The attachment filename pattern to search for.</param>
        /// <param name="targetDirectory">The (writable) directory where a found attachment will be saved.</param>
        /// <returns>True if a matching attachment was found and downloaded. False otherwise.</returns>
        public virtual bool DownloadAttachment(Regex attachmentNamePattern, string targetDirectory)
        {
            //we don't know how many items we'll have to search (likely nowhere near int.MaxValue)
            ItemView view = new ItemView(int.MaxValue);

            //we want the most recently received item
            view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);

            //load the properties required to perform a search for the attachment
            view.PropertySet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.IsRead, EmailMessageSchema.HasAttachments);

            //build the search filter
            SearchFilter filter = new SearchFilter.SearchFilterCollection(
                LogicalOperator.And,
                new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false),
                new SearchFilter.IsEqualTo(EmailMessageSchema.HasAttachments, true)
            );

            //perform the search and return the results as EmailMessage objects
            var results = Inbox.FindItems(filter, view).Cast<EmailMessage>();
            bool foundAttachment = false;

            foreach (var result in results)
            {
                //another call to EWS to actually load in this email's attachment collection
                var email = EmailMessage.Bind(exchangeService, result.Id, new PropertySet(EmailMessageSchema.Attachments));

                foreach (var attachment in email.Attachments)
                {
                    if (attachmentNamePattern.IsMatch(attachment.Name))
                    {
                        FileAttachment fileAttachment = attachment as FileAttachment;
                        if (fileAttachment != null)
                        {
                            //save the attachment to the target directory
                            fileAttachment.Load(Path.Combine(targetDirectory, fileAttachment.Name));
                            //mark the email as read
                            email.IsRead = true;
                            email.Update(ConflictResolutionMode.AlwaysOverwrite);
                            //get outta here!
                            foundAttachment = true;
                            break;
                        }
                    }
                }

                if (foundAttachment) break;
            }

            return foundAttachment;
        }
Ejemplo n.º 34
0
    public void accessShared()
    {
        ServicePointManager.ServerCertificateValidationCallback = m_UrlBack.CertificateValidationCallBack;

            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);

            // Get the information of the account.
            service.Credentials = new WebCredentials(EMAIL_ACCOUNT, EMAIL_PWD);

            // Set the url of server.
            if (!AutodiscoverUrl(service, EMAIL_ACCOUNT))
            {
                return;
            }

            var mb = new Mailbox(SHARED_MAILBOX);

            var fid1 = new FolderId(WellKnownFolderName.Inbox, mb);

            // Add a search filter that searches on the body or subject.
            List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
            searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, SUBJECT_KEY_WORD));
            SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray());

            // Create a view with a page size of 10.
            var view = new ItemView(10);

            // Identify the Subject and DateTimeReceived properties to return.
            // Indicate that the base property will be the item identifier
            view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived);

            // Order the search results by the DateTimeReceived in descending order.
            view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);

            // Set the traversal to shallow. (Shallow is the default option; other options are Associated and SoftDeleted.)
            view.Traversal = ItemTraversal.Shallow;
            String[] invalidStings = { "\\", ",", ":", "*", "?", "\"", "<", ">", "|" };

            PropertySet itemPorpertySet = new PropertySet(BasePropertySet.FirstClassProperties,
                EmailMessageSchema.MimeContent);

            FindItemsResults<Item> findResults = service.FindItems(fid1, searchFilter, view);
            foreach (Item item in findResults.Items)
            {
                EmailMessage email = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));
                email.Load(itemPorpertySet);

                string emailBody = email.Body.ToString();
            }
    }
Ejemplo n.º 35
0
 /// <summary>
 /// This function retuns the mail items for the given folder and for the date
 /// </summary>
 /// <param name="service"></param>
 /// <param name="folderId"></param>
 /// <param name="lastSyncDate"></param>
 /// <returns></returns>
 public FindItemsResults<Item> RetrieveMailItems(ref ExchangeService service, FolderId folderId,
     DateTime lastSyncDate)
 {
     //email view
     var emailView = new ItemView(int.MaxValue) { PropertySet = BasePropertySet.IdOnly };
     //search filter collection
     var searchFilterCollection =
         new SearchFilter.SearchFilterCollection(LogicalOperator.And)
         {
             new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, lastSyncDate)
         };
     //retrieve
     var items = service.FindItems(folderId, searchFilterCollection, emailView);
     return items;
 }
Ejemplo n.º 36
0
        internal List<Item> GetItem(Folder folder, ItemView iView, DateTime startDate, DateTime endDate, string subjectToSearch)
        {
            SearchFilter.SearchFilterCollection searchFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
            searchFilterCollection.Add(new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, startDate));
            searchFilterCollection.Add(new SearchFilter.IsLessThanOrEqualTo(ItemSchema.DateTimeReceived, endDate));

            if (!String.IsNullOrEmpty(subjectToSearch))
            {
                searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, subjectToSearch));
            }

            SearchFilter searchFilter = searchFilterCollection;
            FindItemsResults<Item> findResult = folder.FindItems(searchFilter, iView);

            return this.GetListItem(findResult);
        }
Ejemplo n.º 37
0
        //thread to get all emails
        public static void _getMails(object param)
        {
            helpers.addLog("_getMails() started...");
            ews _ews = (ews)param;  //need an instance
            _ews.OnStateChanged(new StatusEventArgs(StatusType.busy, "_getMails() started..."));
            const int chunkSize = 50;
            try
            {
                PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
                itempropertyset.RequestedBodyType = BodyType.Text; //request plain text body
                //blocking call
                ItemView view = new ItemView(chunkSize);
                view.PropertySet = itempropertyset;

                view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);
                /*
                private static void GetAttachments(ExchangeService service)
                {
                    // Return a single item.
                    ItemView view = new ItemView(1);

                    string querystring = "HasAttachments:true Subject:'Message with Attachments' Kind:email";

                    // Find the first email message in the Inbox that has attachments. This results in a FindItem operation call to EWS.
                    FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.Inbox, querystring, view);

                    if (results.TotalCount > 0)
                    {
                        EmailMessage email = results.Items[0] as EmailMessage;
                */
                FindItemsResults<Item> findResults;

                do
                {
                    //findResults = service.FindItems(WellKnownFolderName.Inbox, view);
                    SearchFilter.SearchFilterCollection filterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
                    filterCollection.Add(new SearchFilter.Not(new SearchFilter.ContainsSubstring(ItemSchema.Subject, sMailHasAlreadyProcessed)));
                    filterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, helpers.filterSubject));
                    filterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Attachments, helpers.filterAttachement));
                    findResults = _ews._service.FindItems(WellKnownFolderName.Inbox, filterCollection, view);

                    _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "getMail: found "+ findResults.Items.Count + " items in inbox"));
                    foreach (Item item in findResults.Items)
                    {
                        helpers.addLog("found item...");
                        if (item is EmailMessage)
                        {
                            EmailMessage mailmessage = item as EmailMessage;
                            mailmessage.Load(itempropertyset); //load data from server

                            helpers.addLog("\t is email ...");

                            // If the item is an e-mail message, write the sender's name.
                            helpers.addLog(mailmessage.Sender.Name + ": " + mailmessage.Subject);
                            _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "getMail: processing eMail " + mailmessage.Subject));

                            MailMsg myMailMsg = new MailMsg(mailmessage, _ews._userData.sUser);

                            // Bind to an existing message using its unique identifier.
                            //EmailMessage message = EmailMessage.Bind(service, new ItemId(item.Id.UniqueId));
                            int iRet = _ews._licenseMail.processMail(myMailMsg);

                            //change subject?
                            // Bind to the existing item, using the ItemId. This method call results in a GetItem call to EWS.
                            Item myItem = Item.Bind(_ews._service, item.Id as ItemId);
                            myItem.Load();
                            // Update the Subject of the email.
                            myItem.Subject += "[processed]";
                            // Save the updated email. This method call results in an UpdateItem call to EWS.
                            myItem.Update(ConflictResolutionMode.AlwaysOverwrite);

                            _ews.OnStateChanged(new StatusEventArgs(StatusType.license_mail, "processed "+iRet.ToString()));
                        }
                    }
                    view.Offset += chunkSize;
                } while (findResults.MoreAvailable && _ews._bRunThread);
                _ews.OnStateChanged(new StatusEventArgs(StatusType.idle, "readmail done"));
            }
            catch (ThreadAbortException ex)
            {
                helpers.addLog("ThreadAbortException: " + ex.Message);
            }
            catch (Exception ex)
            {
                helpers.addLog("Exception: " + ex.Message);
                _ews.OnStateChanged(new StatusEventArgs(StatusType.error, "readmail exception: " + ex.Message));
            }
            helpers.addLog("_getMails() ended");
            _ews.startPull();
        }
Ejemplo n.º 38
0
        public void DeleteMail(string emailId )
        {
            ExchangeService service = new ExchangeService();
            //string emailId = "*****@*****.**"; //  string filesPath5 = ConfigurationManager.AppSettings["UserName"].ToString();
            if (emailId != string.Empty)
            {
                service.Credentials = new WebCredentials(emailId, "Sea2013");
                service.UseDefaultCredentials = false;
                service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
                DateTime searchdate = DateTime.Now;
                searchdate = searchdate.AddDays(-4);

                SearchFilter greaterthanfilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, searchdate);
                SearchFilter lessthanfilter = new SearchFilter.IsLessThan(ItemSchema.DateTimeReceived, searchdate);
                SearchFilter filter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, lessthanfilter);
                Folder folder = Folder.Bind(service, WellKnownFolderName.Inbox);
                //Or the folder you want to search in
                FindItemsResults<Item> results = folder.FindItems(filter, new ItemView(folder.TotalCount));
                foreach (Item i in results.Items)
                {
                    i.Delete(DeleteMode.MoveToDeletedItems);
                }
            }
        }
        private static Folder GetSourceFolder(ExchangeService service, string email)
        {
            // Use the following search filter to get all mail in the Inbox with the word "extended" in the subject line.
            SearchFilter searchCriteria = new SearchFilter.SearchFilterCollection(LogicalOperator.And,
                //Search for Folder DisplayName that matches mailbox email address:
                new SearchFilter.ContainsSubstring(FolderSchema.DisplayName, email.ToLower()));
            FolderView fv = new FolderView(100);
            fv.PropertySet = new PropertySet(BasePropertySet.IdOnly, FolderSchema.DisplayName, FolderSchema.TotalCount);

            // Find the search folder named "MailModder".
            FindFoldersResults findResults = service.FindFolders(
                WellKnownFolderName.Inbox,
                searchCriteria,
                fv);

            //Return root of inbox by default:
            //Folder returnFolder = Folder.Bind(service, WellKnownFolderName.Inbox);

            foreach (Folder searchFolder in findResults)
            {
                if (searchFolder.DisplayName.Contains(email.ToLower()))
                {
                    logger.Debug("Found source folder for email: " + email + ". Using folder: " + searchFolder.DisplayName + searchFolder.TotalCount);
                    return searchFolder;
                }
            }

            logger.Debug("Error getting commissioner source folder; returning global instead for: " + email);
            return GetGlobalFolder(service);
        }
        public static FindItemsResults<Item> GetAllMessages(ExchangeService service, Folder targetFolder, int start, int length, string dateFilter, string fromFilter, string subjectFilter)
        {
            //Create empty list for all mailbox messages:
            var listing = new List<EmailMessage>();

            //Create ItemView with correct pagesize and offset:
            ItemView view = new ItemView(length, start, OffsetBasePoint.Beginning);

            view.PropertySet = new PropertySet(EmailMessageSchema.Id,
                EmailMessageSchema.Subject,
                EmailMessageSchema.DateTimeReceived,
                EmailMessageSchema.From
                );

            view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
            List<SearchFilter> searchANDFilterCollection = new List<SearchFilter>();
            FindItemsResults<Item> findResults;

            if (!string.IsNullOrWhiteSpace(dateFilter))
            {
                string[] dates = dateFilter.Split('~');

                if (!string.IsNullOrWhiteSpace(dates[0]))
                {
                    searchANDFilterCollection.Add(new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.DateTimeReceived, dates[0]));
                }

                if (!string.IsNullOrWhiteSpace(dates[1]))
                {
                    searchANDFilterCollection.Add(new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeReceived, dates[1]));
                }
            }

            if (!string.IsNullOrWhiteSpace(fromFilter))
            {
                searchANDFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.From, fromFilter));
            }

            if (!string.IsNullOrWhiteSpace(subjectFilter))
            {
                searchANDFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, subjectFilter));
            }

            if (searchANDFilterCollection.Count > 0)
            {
                SearchFilter searchANDFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchANDFilterCollection.ToArray());
                findResults = service.FindItems(targetFolder.Id, searchANDFilter, view);
            }
            else
            {
                findResults = service.FindItems(targetFolder.Id, view);
            }

            logger.Debug("FindResults Count = " + findResults.TotalCount);

            //bool MoreItems = true;

            //while(MoreItems)
            //{
                //foreach (EmailMessage it in findResults.Items)
                //{
                //    listing.Add(it);
                //}
            //}

            //return View(listing.ToPagedList<EmailMessage>(pageNumber, pageSize));

            return findResults;
        }
        private List<X> GetMailIdsToProcess(ExchangeService service, FolderId inboxFolder)
        {
            var propertySet = new PropertySet(
                BasePropertySet.IdOnly,
                ItemSchema.Subject,
                ItemSchema.DateTimeReceived);
            propertySet.RequestedBodyType = BodyType.Text;

            var view = new ItemView(50);
            view.PropertySet = propertySet;

            var searchFilters = new List<SearchFilter>()
            {
                new SearchFilter.IsGreaterThan(ItemSchema.DateTimeReceived, DateTime.Today)
            };

            var searchFilter = new SearchFilter.SearchFilterCollection(
                LogicalOperator.And,
                searchFilters.ToArray());

            view.Traversal = ItemTraversal.Shallow;

            var mailIds = new List<X>();

            var mailsToday = service.FindItems(inboxFolder, searchFilter, view);
            if (mailsToday.Count() > 0)
            {
                mailIds.AddRange(mailsToday.Select(mt => new X()
                {
                    ItemId = mt.Id.UniqueId,
                    Subject = mt.Subject
                }));
            }

            while (mailsToday.MoreAvailable)
            {
                mailsToday = service.FindItems(inboxFolder, searchFilter, view);
                if (mailsToday.Count() > 0)
                {
                    mailIds.AddRange(mailsToday.Select(mt => new X()
                    {
                        ItemId = mt.Id.UniqueId,
                        Subject = mt.Subject
                    }));
                }
            }

            return mailIds;
        }
Ejemplo n.º 42
0
        /// <summary>
        /// Instantiate default search filter with start and end date
        /// for item.
        /// </summary>
        /// <returns>SearchFilter</returns>
        private SearchFilter CreateDefaultSearchFilter()
        {
            SearchFilter defaultSearchFilter = new SearchFilter.SearchFilterCollection(
                    LogicalOperator.And,
                    new SearchFilter.IsGreaterThan(ItemSchema.DateTimeCreated, this.startDate),
                    new SearchFilter.IsLessThan(ItemSchema.DateTimeCreated, this.endDate)
                );

            return defaultSearchFilter;
        }
        private static Folder GetSourceFolder(ExchangeService service, EmailAddress email)
        {
            log4net.Config.XmlConfigurator.Configure();

            // Use the following search filter to get all mail in the Inbox with the word "extended" in the subject line.
            SearchFilter searchCriteria = new SearchFilter.SearchFilterCollection(LogicalOperator.And,
                //Search for Folder DisplayName that matches mailbox email address:
                new SearchFilter.IsEqualTo(FolderSchema.DisplayName, email.Address));

            // Find the search folder named "MailModder".
            FindFoldersResults findResults = service.FindFolders(
                WellKnownFolderName.Inbox,
                searchCriteria,
                new FolderView(50));

            //Return root of inbox by default:
            Folder returnFolder = Folder.Bind(service, WellKnownFolderName.Inbox);
            foreach (Folder searchFolder in findResults.Folders)
            {
                if (searchFolder.DisplayName == email.Address)
                {
                    returnFolder = searchFolder;
                }
            }

            return returnFolder;
        }
Ejemplo n.º 44
0
        public List<int> getEmailDeliveryConfirmation()
        {
            List<int> returnList = new List<int>();

            // Add a search filter that searches on the body or subject.
            List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
            searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.ItemClass, "REPORT.IPM.Note.DR"));

            // Create the search filter.
            SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection.ToArray());

            // Create a view with a page size of 100.
            ItemView view = new ItemView(100);

            // Identify the Subject and DateTimeReceived properties to return.
            // Indicate that the base property will be the item identifier
            view.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties);

            // Order the search results by the DateTimeReceived in descending order.
            view.OrderBy.Add(ItemSchema.DateTimeSent, Microsoft.Exchange.WebServices.Data.SortDirection.Descending);

            // Set the traversal to shallow. (Shallow is the default option; other options are Associated and SoftDeleted.)
            view.Traversal = ItemTraversal.Shallow;

            // Send the request to search the Inbox and get the results.
            FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, view);

            if (findResults.Items.Count > 0)
                service.LoadPropertiesForItems(findResults, new PropertySet(ItemSchema.Body, EmailMessageSchema.InReplyTo));

            foreach (EmailMessage mail in findResults.Items)
            {
                EmailMessage parentMail = getSingleEmailByInternetID(mail.InReplyTo);

                if (parentMail.ExtendedProperties.Count > 0)
                    returnList.Add(int.Parse(parentMail.ExtendedProperties[0].Value.ToString()));

                mail.Move(getFolderId("DeliveryConfirmation"));
            }

            return returnList;
        }
Ejemplo n.º 45
0
        private EmailMessage getSingleEmailByInternetID(string id)
        {
            // Add a search filter that searches on the body or subject.
            List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
            searchFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.InternetMessageId, id));

            // Create the search filter.
            SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection.ToArray());

            // Create a view with a page size of 50.
            ItemView view = new ItemView(1);

            // Identify the Subject and DateTimeReceived properties to return.
            // Indicate that the base property will be the item identifier
            view.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.Subject, ItemSchema.Id, ItemSchema.DateTimeReceived, EmailMessageSchema.ItemClass);

            // Order the search results by the DateTimeReceived in descending order.
            view.OrderBy.Add(ItemSchema.DateTimeSent, Microsoft.Exchange.WebServices.Data.SortDirection.Descending);

            // Set the traversal to shallow. (Shallow is the default option; other options are Associated and SoftDeleted.)
            view.Traversal = ItemTraversal.Shallow;

            // Send the request to search the Inbox and get the results.
            FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.SentItems, searchFilter, view);

            if (findResults.Items.Count > 0)
            {
                service.LoadPropertiesForItems(findResults, new PropertySet(new ExtendedPropertyDefinition(DefaultExtendedPropertySet.PublicStrings, "InternalId", MapiPropertyType.String)));
                return findResults.Items[0] as EmailMessage;
            }

            return new EmailMessage(service);
        }
Ejemplo n.º 46
0
        public List<int> getEmailReadConfirmation()
        {
            List<int> returnList = new List<int>();

            // Add a search filter that searches on the body or subject.
            List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
            searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.ItemClass, "REPORT.IPM.Note.IPNRN"));

            // Create the search filter.
            SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection.ToArray());

            // Create a view with a page size of 100.
            ItemView view = new ItemView(100);

            // Identify the Subject and DateTimeReceived properties to return.
            // Indicate that the base property will be the item identifier
            view.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.DateTimeSent);

            // Order the search results by the DateTimeReceived in descending order.
            view.OrderBy.Add(ItemSchema.DateTimeSent, Microsoft.Exchange.WebServices.Data.SortDirection.Descending);

            // Set the traversal to shallow. (Shallow is the default option; other options are Associated and SoftDeleted.)
            view.Traversal = ItemTraversal.Shallow;

            // Send the request to search the Inbox and get the results.
            FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, view);

            if (findResults.Items.Count > 0)
                service.LoadPropertiesForItems(findResults, new PropertySet(ItemSchema.Body, EmailMessageSchema.Subject, EmailMessageSchema.InReplyTo, EmailMessageSchema.ConversationId));

            foreach (EmailMessage mail in findResults.Items)
            {
                int internalId;
                string internalIdString = mail.Subject;

                internalIdString = internalIdString.Substring(internalIdString.IndexOf("Email #:") + 8);
                internalIdString = internalIdString.Substring(0, internalIdString.IndexOf(")"));

                Int32.TryParse(internalIdString, out internalId);

                if (Int32.TryParse(internalIdString, out internalId))
                {
                    returnList.Add(internalId);

                    mail.Move(getFolderId("ReadConfirmation"));
                }
            }

            return returnList;
        }
 private FindFoldersResults FindSubFolders(ExchangeService service,
     WellKnownFolderName parentFolder,
     MailSearchContainerNameList subFolderNames)
 {
     var folderView = new FolderView(VIEW_SIZE);
     folderView.PropertySet = new PropertySet(BasePropertySet.IdOnly, new PropertySet { FolderSchema.DisplayName, FolderSchema.Id });
     Folder rootFolder = Folder.Bind(service, parentFolder);
     var searchFilters = new List<SearchFilter>();
     foreach (var subfolderName in subFolderNames)
     {
         searchFilters.Add(new SearchFilter.ContainsSubstring(FolderSchema.DisplayName,subfolderName));
     }
     var searchFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilters);
     return rootFolder.FindFolders(searchFilterCollection, folderView);
 }
Ejemplo n.º 48
0
        public static FindItemsResults<Item> GetItems(ExchangeService service, string address)
        {
            var searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
            //var searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.Subject, "MyExchangeTest"));

            var mailbox = new Mailbox(address);
            var folderId = new FolderId(WellKnownFolderName.Inbox, mailbox);

            var items = service.FindItems(folderId, searchFilter, new ItemView(5));
            return items;
        }
Ejemplo n.º 49
0
        static void Main(string[] args)
        {
            Thread t = null;
            var reqType = new RequestType();
            try
                {
                if (args[0].Contains("poll"))
                    {
                    reqType = RequestType.Poll;
                    Console.WriteLine("\n\tTrying to connect to Exchange server.");
                    t = new Thread(ShowProgress);
                    t.Start();
                    }
                else if (args[0].Contains("send"))
                    reqType = RequestType.Send;
                else
                    {
                    Console.WriteLine("\n\tAccepted arguments are 'poll' or 'send'");
                    Environment.Exit(1);
                    }
                }
            catch
                {
                Console.WriteLine("\n\tYou have not provided any argument. Give either 'poll' or 'send' as argument.");
                Environment.Exit(1);
                }

            ExchangeService service = new ExchangeService();
            service.Credentials = new WebCredentials("<username>", "<password>", "<domain>");
            service.AutodiscoverUrl("<full email address>", RedirectionUrlValidationCallback);

            if (reqType == RequestType.Poll)
                {
                if (t != null)
                    t.Abort();
                Console.WriteLine("\n\n\tConnected. Polling for a matching email started. Hit Ctrl+C to quit.");
                while (true)
                    {
                    Thread.Sleep(10000);
                    FolderView folderView = new FolderView(int.MaxValue);
                    FindFoldersResults findFolderResults = service.FindFolders(WellKnownFolderName.Inbox, folderView);
                    foreach (Folder folder in findFolderResults)
                        {

                        if (folder.DisplayName == "<Folder name>" && folder.UnreadCount > 0)
                            {
                            SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
                            ItemView view = new ItemView(1);

                            // Fire the query for the unread items.
                            // This method call results in a FindItem call to EWS.
                            FindItemsResults<Item> findResults = service.FindItems(folder.Id, sf, view);
                            var email = (EmailMessage)findResults.Items[0];

                            EmailMessage message = EmailMessage.Bind(service, email.Id, new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.Attachments));
                            mailFrom = message.From.Address;
                            //Console.WriteLine("Name:" + email.From.Name);
                            string subject = email.Subject;

                            Console.WriteLine("\n\tEmail received from : " + mailFrom + " with subject \"" + subject + " at " + DateTime.Now);

                            folder.MarkAllItemsAsRead(true);
                            //Perform the action you want. Example : Go to the desired URL
                            var client = new WebClient();
                            try{
                            client.OpenRead("http://google.com");
                            }
                            catch(Exception e){}
                            }
                        }
                    }
                }
            else if (reqType == RequestType.Send)
                {
                SendEmailWithReport(service, "<To email address>");
                }
        }
        public static FindItemsResults<Item> GetCMessages(ExchangeService service, Folder targetFolder, string[] email, int start, int length, string datefromS, string datetoS, string toS, string fromS, string subjectS, string bodyS, string dateFilter, string fromFilter, string subjectFilter)
        {
            //Create empty list for all mailbox messages:
            var listing = new List<EmailMessage>();

            Folder gsf = gsf = GetGlobalFolder(service);
            FindItemsResults<Item> findResults = null;

            //Create ItemView with correct pagesize and offset:
            ItemView view = new ItemView(length, start, OffsetBasePoint.Beginning);

            view.PropertySet = new PropertySet(EmailMessageSchema.Id,
                EmailMessageSchema.Subject,
                EmailMessageSchema.DateTimeReceived,
                EmailMessageSchema.From
                );
            view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);

            //Define the new PidTagParentDisplay property to use for filtering:
            ExtendedPropertyDefinition def = new ExtendedPropertyDefinition(0x0E05, MapiPropertyType.String);

            List<SearchFilter> searchANDFilterCollection = new List<SearchFilter>();
            List<SearchFilter> searchORcommCollection = new List<SearchFilter>();
            List<SearchFilter> searchCompCollection = new List<SearchFilter>();

            //Add "OR" commissioner search criteria:
            if (email != null && email.Count() > 0)
            {
                foreach (var target in email)
                {
                    string t = target;
                    if (target.Contains('@'))
                    {
                        t = target.Split('@')[0];
                    }

                    searchORcommCollection.Add(new SearchFilter.ContainsSubstring(def, t.ToLower()));
                    logger.Debug("Added mailbox to searchOR collection: " + target);
                }
            }

            if (searchORcommCollection.Count > 0)
            {
                SearchFilter searchOrFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchORcommCollection.ToArray());
                searchCompCollection.Add(searchOrFilter);
            }

            //Populate fields from the SEARCH form (not the filters, just the search):

            if (!string.IsNullOrWhiteSpace(datefromS))
            {
                DateTime dFrom = DateTime.Parse(datefromS + " 12:00AM");
                logger.Debug("datefromS -- " + dFrom.ToString());

                searchANDFilterCollection.Add(new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.DateTimeReceived, dFrom));
            }

            if (!string.IsNullOrWhiteSpace(datetoS))
            {
                DateTime dTo = DateTime.Parse(datetoS + " 11:59PM");
                logger.Debug("datetoS -- " + dTo.ToString());
                searchANDFilterCollection.Add(new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeReceived, dTo));
            }

            if (!string.IsNullOrWhiteSpace(fromS))
            {
                searchANDFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.From, fromS));
            }

            if (!string.IsNullOrWhiteSpace(toS))
            {
                searchANDFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.DisplayTo, toS));
            }

            if (!string.IsNullOrWhiteSpace(subjectS))
            {
                searchANDFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, subjectS));
            }

            if (!string.IsNullOrWhiteSpace(bodyS))
            {
                searchANDFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.Body, bodyS));
            }

            //Populate fields from Datatables FILTER form (this supplements the SEARCH form):

            if (!string.IsNullOrWhiteSpace(dateFilter))
            {
                string[] dates = dateFilter.Split('~');

                if (!string.IsNullOrWhiteSpace(dates[0]))
                {
                    DateTime dfFrom = DateTime.Parse(dates[0] + " 12:00AM");
                    logger.Debug("dfFrom -- " + dfFrom.ToString());
                    searchANDFilterCollection.Add(new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.DateTimeReceived, dfFrom));
                }

                if (!string.IsNullOrWhiteSpace(dates[1]))
                {
                    DateTime dfTo = DateTime.Parse(dates[1] + " 11:59PM");
                    logger.Debug("dfTo -- " + dfTo.ToString());
                    searchANDFilterCollection.Add(new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeReceived, dfTo));
                }
            }

            if (!string.IsNullOrWhiteSpace(fromFilter))
            {
                searchANDFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.From, fromFilter));
            }

            if (!string.IsNullOrWhiteSpace(subjectFilter))
            {
                searchANDFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, subjectFilter));
            }

            //Assemble the SearchFilter Collection

            if (searchANDFilterCollection.Count > 0)
            {
                SearchFilter searchANDFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchANDFilterCollection.ToArray());
                searchCompCollection.Add(searchANDFilter);
            }

            //Evaluate filters and execute find results:

            if (searchORcommCollection.Count > 0 || searchANDFilterCollection.Count > 0)
            {
                SearchFilter searchComp = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchCompCollection.ToArray());
                findResults = service.FindItems(targetFolder.Id, searchComp, view);
            }
            else
            {
                findResults = service.FindItems(targetFolder.Id, view);
            }

            logger.Debug("FindResults Count = " + findResults.TotalCount);

            return findResults;
        }
Ejemplo n.º 51
0
        public void GetAttachments(String fromAddress, String subjectPrefix, String attachementNamePrefix, int mailSearchCount)
        {
            this.log("Searching inbox...");

            List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
            searchFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.From, new EmailAddress(fromAddress)));
            if (subjectPrefix != "")
            {
                searchFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, subjectPrefix, ContainmentMode.Prefixed, ComparisonMode.IgnoreCase));
            }
            SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection.ToArray());

            FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, new ItemView(mailSearchCount));

            this.log("Emails found mathcing search criteria (From=" + fromAddress + " and subject prefix=" + subjectPrefix + ")=" + findResults.TotalCount.ToString());
            this.log("Searching for attachments...");

            foreach (Item item in findResults.Items)
            {
                if (item.HasAttachments)
                {
                    EmailMessage message = EmailMessage.Bind(this.service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));
                    this.log(message.Attachments.Count() + " attachements found in email with ID=" + item.Id);
                    message.Load();
                    this.log("Searching for attachement matching file name prefix=" + attachementNamePrefix + "...");
                    Boolean filesFound = false;
                    foreach (FileAttachment fileAttachment in message.Attachments)
                    {
                        this.log("- - - - - - - - - - - - - Attachment - - - - - - - - - - - - - -");
                        fileAttachment.Load();
                        if (fileAttachment.Name.StartsWith(attachementNamePrefix))
                        {
                            filesFound = true;
                            this.log("Match found on fileName: " + fileAttachment.Name);
                            String path = this.exportpath + fileAttachment.Name;
                            String temppath = path;

                            // rename file by index if exist.
                            int filecount = 0;
                            while (System.IO.File.Exists(temppath))
                            {
                                filecount++;
                                this.log("A file with this name already exist. Trying adding count index " + filecount + " to filename.");
                                temppath = System.IO.Path.GetFileNameWithoutExtension(path) + "_" + filecount.ToString() + System.IO.Path.GetExtension(path);
                            }
                            path = temppath;

                            fileAttachment.Load(path);
                            this.log("Exported attachent to: " + path);
                        }
                    }
                    if (!filesFound)
                    {
                        this.log("No attachment files found!");
                    }
                    this.log("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
                }
            }
        }
        public void SearchEmailOfAccount(string emailAddr)
        {
            //ewsManager.ImpersonateEmailAccount( emailAddr);

            // Get emails in batches
            ItemView itemView = new ItemView(50);

            // only get new emails...  need to remove this filter.
            SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));

            // just want unread items.
            var items =  ewsManager.Service.FindItems(WellKnownFolderName.Inbox, sf, itemView);

            foreach (var item in items)
            {
                EmailMessage message = EmailMessage.Bind( ewsManager.Service, item.Id, new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.Attachments));

                if (message.HasAttachments)
                {
                    foreach (var attachment in message.Attachments)
                    {
                        FileAttachment fa = attachment as FileAttachment;
                        if (fa != null)
                        {
                            fa.Load();
                            var url = CopyAttachmentToAzure(fa);
                            DeleteAttachmentException(message, fa);
                            var newAttachment = CreateAttachment(url, fa.FileName);
                            message.Attachments.AddFileAttachment(newAttachment.Name, newAttachment.Bytes);
                            message.Update(ConflictResolutionMode.AlwaysOverwrite);

                        }
                    }
                }

            }
        }