Example #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)
            {

            }
        }
Example #2
1
        private static void CatchEmails()
        {
            string login = ConfigurationManager.AppSettings["login"];
            string pass = ConfigurationManager.AppSettings["pass"];
            string mail = ConfigurationManager.AppSettings["mail"];
            WebCredentials credentials = new WebCredentials(mail, pass);
            //Client.Credentials = new WebCredentials(login, pass);
            Client.Credentials = credentials;
            Client.UseDefaultCredentials = false;
            Client.AutodiscoverUrl(mail, RedirectionUrlValidationCallback);

            ItemView view = new ItemView(1000000000);//Чтобы ничего не пропустить берем миллиард записей сразу ))

            FindItemsResults<Item> findResults = Client.FindItems(WellKnownFolderName.Inbox, view);

            if (findResults.Any())
            {
                Client.LoadPropertiesForItems(findResults, PropertySet.FirstClassProperties);
                bool send = HolidayWork.CheckTodayIsPreHoliday().SendDelivery;

                foreach (Item item in findResults.Items)
                {
                    if (send)
                    {
                        if (item.Subject.Contains("Автоматический ответ:")) continue;
                        string fullName = item.LastModifiedName;
                        if (fullName.Equals("Microsoft Outlook")) continue;

                        Objects.ResponseMessage responseMessage;
                        bool complete = Confirmation.Save(fullName, out responseMessage);
                        //if (!complete) throw new Exception(responseMessage.ErrorMessage);

                        if (DateTime.Now.Hour < 16 || (DateTime.Now.Hour == 16 && DateTime.Now.Minute <= 3))
                        {
                            if (complete)
                            {
                                item.Delete(DeleteMode.SoftDelete);
                                Confirmation.SendNote(responseMessage.Email);
                            }
                            else
                            {
                                Confirmation.SendError(responseMessage.Email);
                            }
                        }
                        else if (DateTime.Now.Hour > 16)
                        {
                            item.Delete(DeleteMode.SoftDelete);
                            Confirmation.SendEndTime(responseMessage.Email);
                        }
                        else
                        {
                            Confirmation.SendError(responseMessage.Email);
                        }
                    }
                    else
                    {
                        item.Delete(DeleteMode.SoftDelete);
                    }
                }
            }
        }
        public static FindItemsResults<Item> RetrieveTasks()
        {
            // Specify the folder to search, and limit the properties returned in the result.
            TasksFolder tasksfolder = TasksFolder.Bind(service,
                                                        WellKnownFolderName.Tasks,
                                                        new PropertySet(BasePropertySet.FirstClassProperties, FolderSchema.TotalCount));

            // Set the number of items to the smaller of the number of items in the Contacts folder or 1000.
            int numItems = tasksfolder.TotalCount < 1000 ? tasksfolder.TotalCount : 1000;

            // Instantiate the item view with the number of items to retrieve from the contacts folder.
            ItemView view = new ItemView(numItems);

            // To keep the request smaller, send only the display name.
            view.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties, TaskSchema.Subject);

            // Retrieve the items in the Tasks folder
            taskItems = service.FindItems(WellKnownFolderName.Tasks, view);

            // If the subject of the task matches only one item, return that task item.
            if (taskItems.Count() > 1)
            {
                service.LoadPropertiesForItems(taskItems.Items, PropertySet.FirstClassProperties);
                return (FindItemsResults<Item>)taskItems;
            }
            // No tasks, were found.
            else
            {
                return null;
            }
        }
        public static FindItemsResults<Item> GetAllMessages(ExchangeService service, Folder targetFolder, int start, int length)
        {
            //Create empty list for all mailbox messages:
            var listing = new List<EmailMessage>();

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

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

            view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);

            FindItemsResults<Item> findResults = service.FindItems(targetFolder.Id, view);

            //bool MoreItems = true;

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

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

            return findResults;
        }
Example #5
0
        /// <summary>
        /// Loads exchange appointment from exchange, filtered by related <paramref name="activityMetadata"/> to
        /// activity unique identifier.
        /// </summary>
        /// <param name="activityMetadata">Activity instance synchronization metadata.</param>
        /// <returns>If appointment with activity id found, returns <see cref="Exchange.Appointment"/> instance.
        /// Otherwise returns null.</returns>
        private Exchange.Appointment GetAppointmentByLocalIdProperty(SysSyncMetaData activityMetadata)
        {
            var localId             = activityMetadata.LocalId;
            var filters             = new Exchange.SearchFilter.SearchFilterCollection(Exchange.LogicalOperator.And);
            var customPropSetFilter = new Exchange.SearchFilter.IsEqualTo(ExchangeUtilityImpl.LocalIdProperty, localId.ToString());

            filters.Add(customPropSetFilter);
            foreach (var noteFolder in Folders)
            {
                Exchange.PropertySet idOnlyPropertySet = new Exchange.PropertySet(Exchange.BasePropertySet.IdOnly);
                var itemView = new Exchange.ItemView(1)
                {
                    PropertySet = idOnlyPropertySet
                };
                IEnumerable <Exchange.Item> itemCollection = GetCalendarItemsByFilter(noteFolder, filters, itemView);
                if (itemCollection == null)
                {
                    continue;
                }
                foreach (Exchange.Item item in itemCollection)
                {
                    Exchange.Appointment appointment = SafeBindItem <Exchange.Appointment>(Service, item.Id);
                    if (appointment != null)
                    {
                        return(appointment);
                    }
                }
            }
            return(null);
        }
        static IEnumerable<Microsoft.Exchange.WebServices.Data.Task> FindIncompleteTask(ExchangeService service)
        {
            // Specify the folder to search, and limit the properties returned in the result.
            TasksFolder tasksfolder = TasksFolder.Bind(service,
                                                       WellKnownFolderName.Tasks,
                                                       new PropertySet(BasePropertySet.IdOnly, FolderSchema.TotalCount));

            // Set the number of items to the smaller of the number of items in the Contacts folder or 1000.
            int numItems = tasksfolder.TotalCount < 1000 ? tasksfolder.TotalCount : 1000;

            // Instantiate the item view with the number of items to retrieve from the contacts folder.
            ItemView view = new ItemView(numItems);

            // To keep the request smaller, send only the display name.
            view.PropertySet = new PropertySet(BasePropertySet.IdOnly, TaskSchema.Subject, TaskSchema.Status, TaskSchema.StartDate);

            var filter = new SearchFilter.IsGreaterThan(TaskSchema.DateTimeCreated, DateTime.Now.AddYears(-10));

            // Retrieve the items in the Tasks folder with the properties you selected.
            FindItemsResults<Microsoft.Exchange.WebServices.Data.Item> taskItems = service.FindItems(WellKnownFolderName.Tasks, filter, view);

            // If the subject of the task matches only one item, return that task item.
            var results = new List<Microsoft.Exchange.WebServices.Data.Task>();
            foreach (var task in taskItems)
            {
                var result = new Microsoft.Exchange.WebServices.Data.Task(service);
                result = task as Microsoft.Exchange.WebServices.Data.Task;
                results.Add(result);
            }
            return results;
        }
Example #7
0
        internal List<Contact> GetContact(string something)
        {
            ExchangeService ewsSession = this.GetSessionVariable();
            List<Contact> contacts = new List<Contact>();
            Folder contactFolder = XEwsFolderCmdlet.GetWellKnownFolder(WellKnownFolderName.Contacts, ewsSession);

            int numberOfContacts = 50;
            ItemView iView = new ItemView(numberOfContacts);
            iView.PropertySet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName);

            FindItemsResults<Item> findContacts;

            do
            {
                findContacts = ewsSession.FindItems(contactFolder.Id, iView);

                foreach (Item item in findContacts)
                {
                    if (item is Contact)
                    {
                        Contact contact = item as Contact;
                        contacts.Add(contact);
                    }
                }

                iView.Offset += 50;

            } while (findContacts.MoreAvailable);

            return contacts;
        }
        /// <summary>
        /// For each specified sahred mailbox, if the user has access to the mailbox, 
        /// items matching the search term are sought-out. Each of the specified folders in the user's personal mailbox are also searched.
        /// </summary>
        /// <param name="credentials">The user credntials to impersonate in the mail system.</param>
        /// <param name="sharedMailBoxNames">The names of the shared mailboxes to search.</param>
        /// <param name="mailFolderNames">The names of the folders in the user's personal mail box to search.</param>
        /// <param name="searchTerm">The term that results must contain. This is case insensitive.</param>
        /// <returns>Mail items that match the search term or an empty result (i.e. never null).</returns>
        public IEnumerable<MailItem> FindItems(MailBoxCredentials credentials,
            MailSearchContainerNameList sharedMailBoxNames,
            MailSearchContainerNameList mailFolderNames,
            string searchTerm)
        {
            if (credentials == null
                || String.IsNullOrEmpty(credentials.UserName))
            {
                throw new UnauthorizedAccessException("No user to impersonate specified.");
            }

            var result = new List<MailItem>();
            if (String.IsNullOrEmpty(searchTerm)
                || ((sharedMailBoxNames == null
                     || sharedMailBoxNames.Count <= 0)
                    && (mailFolderNames == null
                     || mailFolderNames.Count <= 0)))
            {
                return result;
            }

            var ewsURL = configuration.EWSURL;
            var networkDomain = configuration.EWSNetworkDomain;
            var networkUserName = configuration.EWSNetworkUserName;
            var networkPassword = configuration.EWSNetworkPassword;
            var mailDomain = configuration.MailDomain;
            var searchFilters = new Microsoft.Exchange.WebServices.Data.SearchFilter.SearchFilterCollection (LogicalOperator.Or,
                    new SearchFilter[5]{new SearchFilter.ContainsSubstring(EmailMessageSchema.Body, searchTerm),
                                        new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, searchTerm),
                                        new SearchFilter.ContainsSubstring(EmailMessageSchema.Sender, searchTerm),
                                        new SearchFilter.ContainsSubstring(EmailMessageSchema.ToRecipients, searchTerm),
                                        new SearchFilter.ContainsSubstring(EmailMessageSchema.Attachments, searchTerm)
                                        });
            var service = ConfigureMSExchangeService(networkUserName,
                                                     networkPassword,
                                                     networkDomain,
                                                     ewsURL,
                                                     credentials);
            var iv = new ItemView(VIEW_SIZE);
            iv.PropertySet = new PropertySet(BasePropertySet.IdOnly,
                                            ItemSchema.Subject,
                                            ItemSchema.DateTimeReceived);

            var shareMailBoxMatches = SearchSharedMailBoxes(service,
                                                            iv,
                                                            searchFilters,
                                                            sharedMailBoxNames,
                                                            configuration.MailDomain,
                                                            searchTerm);
            if (sharedMailBoxNames != null) result.AddRange(shareMailBoxMatches);
            var mailFolderMatches = SearchMailFolders(service,
                                                     iv,
                                                     searchFilters,
                                                     mailFolderNames,
                                                     searchTerm);
            if (mailFolderMatches != null) result.AddRange(mailFolderMatches);

            return result;
        }
Example #9
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?
                            }
                        }
                    }
                }
            }
        }
Example #10
0
        /// <summary>
        /// <see cref="ExchangeSyncProvider.GetItemsFromFolders"/>
        /// </summary>
        protected override List <IRemoteItem> GetItemsFromFolders()
        {
            List <IRemoteItem> result = new List <IRemoteItem>();
            int currentFolderIndex    = 0;

            if (_currentFolder != null)
            {
                currentFolderIndex = _folderCollection.FindIndex(x => GetFolderId(x) == GetFolderId(_currentFolder));
            }
            var numberSkippedFolders = Convert.ToInt32(_isCurrentFolderProcessed) + currentFolderIndex;

            foreach (var noteFolder in _folderCollection.Skip(numberSkippedFolders))
            {
                _isCurrentFolderProcessed = false;
                _currentFolder            = noteFolder;
                var activityFolderIds = new List <Guid>();
                if (UserSettings.RootFolderId != Guid.Empty)
                {
                    activityFolderIds.Add(UserSettings.RootFolderId);
                }
                var folderId = GetFolderId(noteFolder);
                if (UserSettings.RemoteFolderUIds.ContainsKey(folderId))
                {
                    activityFolderIds.Add(UserSettings.RemoteFolderUIds[folderId]);
                }
                Exchange.PropertySet idOnlyPropertySet = new Exchange.PropertySet(Exchange.BasePropertySet.IdOnly);
                var itemView = new Exchange.ItemView(PageItemCount)
                {
                    PropertySet = idOnlyPropertySet,
                    Offset      = PageNumber * PageElementsCount
                };
                Exchange.FindItemsResults <Exchange.Item> itemCollection;
                bool isMaxCountElements = false;
                bool isMoreAvailable    = false;
                do
                {
                    itemCollection = GetFolderItemsByFilter(noteFolder, _itemsFilterCollection, itemView);
                    result.AddRange(GetEmailsFromCollection(itemCollection, activityFolderIds));
                    isMaxCountElements = (result.Count < PageElementsCount);
                    isMoreAvailable    = GetMoreAvailable(itemCollection);
                } while (isMoreAvailable && isMaxCountElements);
                if (!isMoreAvailable)
                {
                    _isCurrentFolderProcessed = true;
                    PageNumber = 0;
                }
                if (!isMaxCountElements)
                {
                    PageNumber++;
                    break;
                }
            }
            return(result);
        }
        public string actualizarRevisionDirectivaE(string asunto, string fechaInicio, string fechaLimite, string cuerpoTarea, string ubicacion)
        {
            string error = "";
            try
            {
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
                service.UseDefaultCredentials = true;

                service.Credentials = new WebCredentials("xxxxxxxxxxxx", "xxxxx", "xxxx");//@uanl.mx
                service.AutodiscoverUrl("xxxxxxxxxxxxxxxxx");

                string querystring = "Subject:'"+asunto +"'";
                ItemView view = new ItemView(1);

                FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.Calendar, querystring, view);// <<--- Esta parte no la se pasar a VB
                if (results.TotalCount > 0)
                {
                    if (results.Items[0] is Appointment) //if is an appointment, could be other different than appointment
                    {
                        Appointment appointment = results.Items[0] as Appointment; //<<--- Esta parte no la se pasar a VB

                        if (appointment.MeetingRequestWasSent)//if was send I will update the meeting
                        {

                            appointment.Start = Convert.ToDateTime(fechaInicio);
                            appointment.End = Convert.ToDateTime(fechaLimite);
                            appointment.Body = cuerpoTarea;
                            appointment.Location = ubicacion;
                            appointment.Update(ConflictResolutionMode.AutoResolve);
                        }
                        else//if not, i will modify and sent it
                        {
                            appointment.Start = Convert.ToDateTime(fechaInicio);
                            appointment.End = Convert.ToDateTime(fechaLimite);
                            appointment.Body = cuerpoTarea;
                            appointment.Location = ubicacion;
                            appointment.Save(SendInvitationsMode.SendOnlyToAll);
                        }
                    }
                }
                else
                {
                    error = "Wasn't found it's appointment";
                    return error;
                }
                return error;
            }
            catch
            {
                return error = "an error happend";
            }
        }
Example #12
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;
        }
Example #13
0
        /// <summary>
        /// Returns all items by <paramref name="filter"/> from <paramref name="folder"/>. Recurring apointments not included.
        /// </summary>
        /// <param name="folder"><see cref=" Exchange.Folder"/> instance.</param>
        /// <param name="filter"><see cref=" Exchange.SearchFilter"/> instance.</param>
        /// <returns><see cref="Exchange.Item"/> collection.</returns>
        protected IEnumerable <Exchange.Item> GetCalendarItems(Exchange.Folder folder, Exchange.SearchFilter filter)
        {
            var itemView = new Exchange.ItemView(PageItemCount);

            Exchange.FindItemsResults <Exchange.Item> itemCollection;
            do
            {
                itemCollection = folder.ReadItems(filter, itemView);
                foreach (var item in itemCollection)
                {
                    yield return(item);
                }
            } while (itemCollection.MoreAvailable);
        }
Example #14
0
        /// <summary>
        /// <see cref="ExchangeSyncProvider.EnumerateChanges"/>
        /// </summary>
        public override IEnumerable <IRemoteItem> EnumerateChanges(SyncContext context)
        {
            base.EnumerateChanges(context);
            var result = new List <IRemoteItem>();

            if (!UserSettings.ImportActivities)
            {
                return(result);
            }
            var folders = new List <Exchange.Folder>();

            Exchange.FolderId trashFolderId = Exchange.Folder.Bind(
                Service, Exchange.WellKnownFolderName.DeletedItems, Exchange.BasePropertySet.IdOnly).Id;
            if (UserSettings.ImportActivitiesAll)
            {
                Exchange.Folder rootFolder = Exchange.Folder.Bind(Service, Exchange.WellKnownFolderName.MsgFolderRoot);
                folders.GetAllFoldersByFilter(rootFolder);
                folders.Add(rootFolder);
            }
            else
            {
                folders = SafeBindFolders(Service, UserSettings.RemoteFolderUIds.Keys, context);
            }
            Exchange.SearchFilter itemsFilter = GetItemsSearchFilters();
            SyncItemSchema        schema      = FindSchemaBySyncValueName(typeof(ExchangeTask).Name);

            foreach (Exchange.Folder folder in folders)
            {
                if (folder.Id.Equals(trashFolderId))
                {
                    continue;
                }
                var itemView = new Exchange.ItemView(PageItemCount);
                Exchange.FindItemsResults <Exchange.Item> itemCollection;
                do
                {
                    itemCollection = folder.ReadItems(itemsFilter, itemView);
                    foreach (Exchange.Item item in itemCollection)
                    {
                        Exchange.Task task = ExchangeUtility.SafeBindItem <Exchange.Task>(Service, item.Id);
                        if (task != null)
                        {
                            var remoteItem = new ExchangeTask(schema, task, TimeZone);
                            result.Add(remoteItem);
                        }
                    }
                } while (itemCollection.MoreAvailable);
            }
            return(result);
        }
 public int GetPendingMessagesCount()
 {
     try
     {
         var inbox    = new ex.FolderId(ex.WellKnownFolderName.Inbox, new ex.Mailbox(Config["NOME_CAIXA"]));
         var itemView = new ex.ItemView(Config["QTD_EMAILS_RECUPERAR"].To(10));
         var items    = GetExchangeService(Username, Password).FindItems(inbox, itemView);
         return(items.Count());
     }
     catch
     {
         Instance = null;
         throw;
     }
 }
 /// <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;
 }
Example #17
0
        public IEnumerable<IIncomingEmailMessage> GetMessages()
        {
            var itemCount = _folder.TotalCount;
            if (itemCount <= 0)
            {
                return new List<IIncomingEmailMessage>();
            }

            var view = new ItemView(itemCount);
            var items = _folder.FindItems(view);

            return items
                    .Where(item => item is EmailMessage) // Return only email message items - ignore any other items
                    .Select(item => new EWSIncomingMessage((EmailMessage) item)); // And wrap them with EWSIncomingMessage
        }
Example #18
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);
        }
        public string ActualizarRevisionDirectivaCorreosE(string asunto, List<string> invitados )
        {
            string error = "";
            try
            {
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
                service.UseDefaultCredentials = true;
                service.Credentials = new WebCredentials("xxxxxxxxxxxxx", "xxxx", "xxxx");
                service.AutodiscoverUrl("xxxxxxxxxxxxxxxxxxxx");

                string querystring = "Subject:'" + asunto + "'";
                ItemView view = new ItemView(1);

                FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.Calendar, querystring, view);// <<--- Esta parte no la se pasar a VB
                if (results.TotalCount > 0)
                {
                    if (results.Items[0] is Appointment) //if is an appointment, could be other different than appointment
                    {
                        Appointment appointment = results.Items[0] as Appointment; //<<--- Esta parte no la se pasar a VB

                        if (appointment.MeetingRequestWasSent)//if was send I will update the meeting
                        {
                           foreach (string invitado in invitados){
                               appointment.RequiredAttendees.Add(invitado);
                           }
                            appointment.Update(ConflictResolutionMode.AutoResolve);
                        }
                        else//if not, i will modify and sent it
                        {
                            appointment.Save(SendInvitationsMode.SendOnlyToAll);
                        }
                    }
                }
                else
                {
                    error = "Wasn't found it's appointment";
                    return error;
                }
                return error;
            }
            catch (Exception ex)
            {
                return error = ex.Message;
            }
        }
        public IEnumerable <MailMessage> GetPendingMessages()
        {
            var inbox    = new ex.FolderId(ex.WellKnownFolderName.Inbox, new ex.Mailbox(Config["NOME_CAIXA"]));
            var itemView = new ex.ItemView(Config["QTD_EMAILS_RECUPERAR"].To(10))
            {
                PropertySet = new ex.PropertySet(ex.BasePropertySet.IdOnly, ex.ItemSchema.Subject,
                                                 ex.ItemSchema.DateTimeReceived)
            };

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

            var findResults = GetExchangeService(Username, Password).FindItems(inbox, itemView);

            var items = GetExchangeService(Username, Password).BindToItems(findResults.Select(item => item.Id),
                                                                           new ex.PropertySet(ex.BasePropertySet.FirstClassProperties,
                                                                                              ex.EmailMessageSchema.From,
                                                                                              ex.EmailMessageSchema.ToRecipients,
                                                                                              ex.ItemSchema.Attachments,
                                                                                              ex.EmailMessageSchema.CcRecipients,
                                                                                              ex.EmailMessageSchema.BccRecipients,
                                                                                              ex.ItemSchema.Body,
                                                                                              ex.ItemSchema.DateTimeCreated,
                                                                                              ex.ItemSchema.DateTimeReceived,
                                                                                              ex.ItemSchema.DateTimeSent,
                                                                                              ex.ItemSchema.DisplayCc,
                                                                                              ex.ItemSchema.DisplayTo,
                                                                                              ex.ItemSchema.Subject));

            foreach (var item in items)
            {
                yield return(ParseItem(item));

                var ea = new OnMessageReadEventArgs();
                if (OnMessageRead != null)
                {
                    OnMessageRead(this, ea);
                    if (ea.Cancel)
                    {
                        continue;
                    }
                }
                GetExchangeService(Username, Password).DeleteItems(new[] { item.Item.Id }, ex.DeleteMode.MoveToDeletedItems, null, null);
            }
        }
        public IEnumerable<MailMessage> GetPendingMessages()
        {
            ex.FolderId inbox = new ex.FolderId(ex.WellKnownFolderName.Inbox, new ex.Mailbox(_config["NOME_CAIXA"]));
            ex.ItemView itemView = new ex.ItemView(_config["QTD_EMAILS_RECUPERAR"].To<int>(10));
            itemView.PropertySet = new ex.PropertySet(ex.BasePropertySet.IdOnly, ex.ItemSchema.Subject, ex.ItemSchema.DateTimeReceived);

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

            ex.FindItemsResults<ex.Item> findResults = GetExchangeService(this.Username, this.Password).FindItems(inbox, itemView);

            ex.ServiceResponseCollection<ex.GetItemResponse> items = GetExchangeService(this.Username, this.Password).BindToItems(findResults.Select(item => item.Id), new ex.PropertySet(ex.BasePropertySet.FirstClassProperties,
                ex.EmailMessageSchema.From,
                ex.EmailMessageSchema.ToRecipients,
                ex.EmailMessageSchema.Attachments,
                ex.EmailMessageSchema.CcRecipients,
                ex.EmailMessageSchema.BccRecipients,
                ex.EmailMessageSchema.Body,
                ex.EmailMessageSchema.DateTimeCreated,
                ex.EmailMessageSchema.DateTimeReceived,
                ex.EmailMessageSchema.DateTimeSent,
                ex.EmailMessageSchema.DisplayCc,
                ex.EmailMessageSchema.DisplayTo,
                ex.EmailMessageSchema.Subject));

            foreach (ex.GetItemResponse item in items)
            {
                yield return ParseItem(item);
                OnMessageReadEventArgs ea = new OnMessageReadEventArgs();
                if (OnMessageRead != null)
                {
                    OnMessageRead(this, ea);
                    if (ea.Cancel)
                        continue;
                }
                GetExchangeService(this.Username, this.Password).DeleteItems(new ex.ItemId[] { item.Item.Id }, ex.DeleteMode.MoveToDeletedItems, null, null);

            }

        }
 static void MarkAllAsRead(Folder folder)
 {
     if (folder.ChildFolderCount == 0)
     {
         ItemView itemView = new ItemView(100);
         itemView.PropertySet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.IsRead);
         SearchFilter filter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
         folder.FindItems(filter, itemView)
               .Cast<EmailMessage>()
               .ToList()
               .ForEach(item =>
         {
             item.IsRead = true;
             item.Update(ConflictResolutionMode.AutoResolve);
         });
     }
     else
     {
         FolderView folderView = new FolderView(folder.ChildFolderCount);
         folder.FindFolders(folderView).ToList().ForEach(child => MarkAllAsRead(child));
     }
 }
Example #23
0
        public void ConnectToExchange()
        {
            ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
            ExchangeService es = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
            es.UseDefaultCredentials = true;
            es.Credentials = new WebCredentials("*****@*****.**", "bulova1");
            es.Url = new Uri("https://mymail.amfam.net/");

            // Query the unread messages
            try
            {
                ItemView view = new ItemView(20);
                FindItemsResults<Item> findResults = es.FindItems(WellKnownFolderName.Inbox, view);

                foreach (EmailMessage m in findResults)
                {
                    if (m.HasAttachments)
                    {
                        foreach (Attachment atmt in m.Attachments)
                        {
                            this.Eatmt = atmt;
                        }

                        // TODO :: Load file name into a database and Load file attachments into a directory
                        updateEAppsTable(m.From.ToString(), m.Subject.ToString(), (DateTime)m.DateTimeReceived, (DateTime)m.DateTimeSent, this.Eatmt);
                    }
                    else
                    {
                        // TODO :: POST to database.
                        updateEAppsTable(m.From.ToString(), m.Subject.ToString(), (DateTime)m.DateTimeReceived, (DateTime)m.DateTimeSent);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }
        public  bool CreateCalendarEvent(ExchangeService service,Appointment objAppointment,string[] rqdAttendeelist,string[] optionalAttendeelist)
        {          
            try
            {             

                ItemView itemView = new ItemView(100);
                itemView.PropertySet = new PropertySet(BasePropertySet.IdOnly);
                List<Appointment> ToCreate = new List<Appointment>();
                Appointment appointment = new Appointment(service);
                appointment.Subject = objAppointment.Subject;// "Calendar Request from Console App";
                appointment.Location = objAppointment.Location;// "Office365";
                appointment.Start = TimeZoneInfo.ConvertTimeToUtc(objAppointment.Start, TimeZoneInfo.Local);
                appointment.End = TimeZoneInfo.ConvertTimeToUtc(objAppointment.End, TimeZoneInfo.Local);// objAppointment.End;
                appointment.Body = objAppointment.Body;
                appointment.IsReminderSet = objAppointment.IsReminderSet;           
                appointment.IsResponseRequested = false;
                foreach(string req in rqdAttendeelist)
                {
                    appointment.RequiredAttendees.Add(req);
                }
                foreach (string opt in optionalAttendeelist)
                {
                    appointment.OptionalAttendees.Add(opt);
                }
                ToCreate.Add(appointment);
                ServiceResponseCollection<ServiceResponse> CreateResponse = service.CreateItems(ToCreate, WellKnownFolderName.Calendar, MessageDisposition.SaveOnly, SendInvitationsMode.SendOnlyToAll);
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                service = null;
            }
        }
        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);

                        }
                    }
                }

            }
        }
Example #26
0
 /// <summary>
 /// Gets Items from <see cref="folder"/> by <see cref="filterCollection"/>
 /// </summary>
 /// <param name="folder">Exchange folder.</param>
 /// <param name="filterCollection">Filter collection.</param>
 /// <param name="itemView">Represents the view settings in a folder search operation.</param>
 /// <returns>Search result collection.</returns>
 public virtual IEnumerable <Exchange.Item> GetCalendarItemsByFilter(Exchange.Folder folder,
                                                                     Exchange.SearchFilter.SearchFilterCollection filterCollection, Exchange.ItemView itemView)
 {
     return(GetFolderItemsByFilter(folder, filterCollection, itemView));
 }
Example #27
0
        /// <summary>
        /// Obtains a list of items by searching the contents of this folder. Calling this method results in a call to EWS.
        /// </summary>
        /// <param name="searchFilter">The search filter. Available search filter classes
        /// include SearchFilter.IsEqualTo, SearchFilter.ContainsSubstring and
        /// SearchFilter.SearchFilterCollection</param>
        /// <param name="view">The view controlling the number of items returned.</param>
        /// <returns>An object representing the results of the search operation.</returns>
        public async Task <FindItemsResults <Item> > FindItems(SearchFilter searchFilter, ItemView view, CancellationToken token = default(CancellationToken))
        {
            EwsUtilities.ValidateParamAllowNull(searchFilter, "searchFilter");

            ServiceResponseCollection <FindItemResponse <Item> > responses = await this.InternalFindItems <Item>(
                searchFilter,
                view,
                null /* groupBy */,
                token).ConfigureAwait(false);

            return(responses[0].Results);
        }
Example #28
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // access master page from nested master page
            Protected.ClaimRuler masterPage = Master.Master as Protected.ClaimRuler;

            // check user permission
            //masterPage.checkPermission();

            clientID = SessionHelper.getClientId();

            // get current lead
            leadID = SessionHelper.getLeadId();

            // get current lead id
            claimID = SessionHelper.getClaimID();

            // get current user
            userID = SessionHelper.getUserId();

            // set directory where client can upload pictures for signature
            txtSignature.UploadedFilesDirectory = appPath + "/clientLogo/" + clientID;

            if (!Page.IsPostBack) {
                bindData();
                userID = SessionHelper.getUserId();

                CRM.Data.Entities.SecUser secUser = SecUserManager.GetByUserId(userID);
                string email = secUser.Email;
                string password =SecurityManager.Decrypt(secUser.emailPassword);
                string url = "https://" + secUser.emailHost + "/EWS/Exchange.asmx";

                try
                {
                    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                    service.Credentials = new WebCredentials(email, password);
                    service.Url = new Uri(url);

                    ContactsFolder contactsfolder = ContactsFolder.Bind(service, WellKnownFolderName.Contacts);

                    int numItems = contactsfolder.TotalCount < 50 ? contactsfolder.TotalCount : 50;

                    ItemView view = new ItemView(int.MaxValue);

                    view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName);

                    FindItemsResults<Item> contactItems = service.FindItems(WellKnownFolderName.Contacts, view);

                    DataTable table = new DataTable();
                    table.Columns.Add("FirstName", typeof(string));
                    table.Columns.Add("LastName", typeof(string));
                    table.Columns.Add("CompanyName", typeof(string));
                    table.Columns.Add("Email", typeof(string));
                    table.Columns.Add("ContactType", typeof(string));

                    foreach (GridRecord crow in contractGrid.Rows)
                    {
                        DataRow row = table.NewRow();
                        row[0] = crow.Items[0].Text;
                        row[1] = crow.Items[1].Text;
                        //row[2] = crow.Cells[2].Text;
                        row[3] = crow.Items[3].Text;
                        row[4] = crow.Items[4].Text;
                        table.Rows.Add(row);
                    }
                    foreach (Item item in contactItems)
                    {
                        if (item is Microsoft.Exchange.WebServices.Data.Contact)
                        {
                            item.Load();
                            Microsoft.Exchange.WebServices.Data.Contact contact = item as Microsoft.Exchange.WebServices.Data.Contact;

                            DataRow row = table.NewRow();
                            row[0] = contact.GivenName;
                            row[1] =contact.Surname;
                            row[3] =contact.EmailAddresses[0].Address;
                            row[4] ="Outlook";
                            table.Rows.Add(row);
                        }
                    }
                    contractGrid.DataSourceID = null;
                    contractGrid.Columns.Clear();
                    contractGrid.DataBind();
                    contractGrid.DataSource = table;
                    contractGrid.DataBind();
                }
                catch (Exception ex)
                {

                }
            }
        }
        private List<Item> GetItems(ExchangeService service, SearchFilter filter, WellKnownFolderName folder, PropertySet propertySet)
        {
            if (service == null)
            {
                return null;
            }

            List<Item> items = new List<Item>();

            if (propertySet == null)
            {
                propertySet = new PropertySet(BasePropertySet.IdOnly);
            }

            const Int32 pageSize = 50;
            ItemView itemView = new ItemView(pageSize);
            itemView.PropertySet = propertySet;

            FindItemsResults<Item> searchResults = null;
            try
            {
                do
                {
                    searchResults = service.FindItems(folder,
                        filter, itemView);
                    items.AddRange(searchResults.Items);

                    itemView.Offset += pageSize;
                } while (searchResults.MoreAvailable);
            }
            catch (Exception ex)
            {
                NotifyDownloadStatus(DownloadStatus.INFORM, ex.Message);
                return null;
            }
            return items;
        }
Example #30
0
        private static List<ItemId> GetItemIds(Folder source, ExchangeService service, ItemTraversal traversal)
        {
            // Collect the Ids of all the items in the folder
            List<ItemId> itemIds = new List<ItemId>();

            FindItemsResults<Item> findResults = null;
            while (findResults == null || findResults.MoreAvailable == true)
            {
                DebugLog.WriteVerbose("Calling FindItems.");

                ItemView view = new ItemView(
                    GlobalSettings.DumpFolderViewSize,
                    itemIds.Count);

                view.Traversal = traversal;
                view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
                findResults = source.FindItems(view);

                DebugLog.WriteVerbose(String.Concat("FindItems returned {0} items", findResults.Items.Count));

                foreach (Item foundItem in findResults.Items)
                {
                    itemIds.Add(foundItem.Id);
                }
            }

            return itemIds;
        }
        private List<Item> GetItems(ExchangeService service, SearchFilter filter, WellKnownFolderName folder, PropertySet propertySet)
        {
            if (service == null)
            {
                return null;
            }

            List<Item> items = new List<Item>();

            if (propertySet == null)
            {
                propertySet = new PropertySet(BasePropertySet.IdOnly);
            }

            const Int32 pageSize = 50;
            ItemView itemView = new ItemView(pageSize);
            itemView.PropertySet = propertySet;

            FindItemsResults<Item> searchResults = null;
            try
            {
                do
                {
                    searchResults = service.FindItems(folder,
                        filter, itemView);
                    items.AddRange(searchResults.Items);

                    itemView.Offset += pageSize;
                } while (searchResults.MoreAvailable);
            }
            catch (Exception ex)
            {
                if (!CheckServerConnection(domain))
                {
                    NotifyDownloadStatus(DownloadStatus.INFORM, "Unable to connect to Exchange server. Please check.");
                }
                else
                {
                    NotifyDownloadStatus(DownloadStatus.INFORM, "The username or password is incorrect. Please try again.");
                }
                return null;
            }
            return items;
        }
        private List<Item> GetItems(ExchangeService service, SearchFilter filter, WellKnownFolderName folder, PropertySet propertySet)
        {
            if (service == null)
            {
                return null;
            }

            List<Item> items = new List<Item>();

            if (propertySet == null)
            {
                propertySet = new PropertySet(BasePropertySet.IdOnly);
            }

            const Int32 pageSize = 50;
            ItemView itemView = new ItemView(pageSize);
            itemView.PropertySet = propertySet;

            FindItemsResults<Item> searchResults = null;
            try
            {
                do
                {
                    searchResults = service.FindItems(folder,
                        filter, itemView);
                    items.AddRange(searchResults.Items);

                    itemView.Offset += pageSize;
                } while (searchResults.MoreAvailable);
            }
            catch (Exception ex)
            {
                if (!CheckServerConnection(domain))
                {
                    NotifyDownloadStatus(DownloadStatus.INFORM, CMController.Properties.Resources.unconnect_exchange_server);
                    return null;
                }
                else
                {
                    NotifyDownloadStatus(DownloadStatus.INFORM, CMController.Properties.Resources.wrong_username_password);
                    return null;
                }
            }
            return items;
        }
 /// <summary>
 /// Gets Items from <see cref="folder"/> by <see cref="filterCollection"/>
 /// </summary>
 /// <param name="folder">Exchange folder.</param>
 /// <param name="filterCollection">Filter collection.</param>
 /// <param name="itemView">Represents the view settings in a folder search operation.</param>
 /// <returns></returns>
 public virtual Exchange.FindItemsResults <Exchange.Item> GetFolderItemsByFilter(Exchange.Folder folder,
                                                                                 Exchange.SearchFilter.SearchFilterCollection filterCollection, Exchange.ItemView itemView)
 {
     return(folder.ReadItems(filterCollection, itemView));
 }
        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;
        }
        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;
        }
        public static List <IEmailMessage> GetIncomingEmails(
            string address,
            bool loadHtmlBody = false,
            CancellationToken cancellationToken = default)
        {
            Contract.Requires(!String.IsNullOrEmpty(address));

            var settings = GetConnectionSettings(address);

            List <IEmailMessage> GetEmails()
            {
                var service = new EWS.ExchangeService(settings.Version)
                {
                    Url = new Uri(settings.Url)
                };

                if (settings.UseDefaultCredentials)
                {
                    service.UseDefaultCredentials = true;
                }
                else
                {
                    service.Credentials = new NetworkCredential(settings.UserName, settings.Password, settings.Domain);
                }
                var mailbox       = new EWS.Mailbox(address);
                var inboxFolderId = new EWS.FolderId(EWS.WellKnownFolderName.Inbox, mailbox);
                var propertySet   = new EWS.PropertySet(EWS.BasePropertySet.FirstClassProperties)
                {
                    RequestedBodyType = EWS.BodyType.Text
                };

                if (loadHtmlBody)
                {
                    propertySet.Add(new EWS.ExtendedPropertyDefinition(ExtendedProperty_HtmlBody, EWS.MapiPropertyType.Binary));
                }
                propertySet.Add(new EWS.ExtendedPropertyDefinition(ExtendedProperty_ConversationId, EWS.MapiPropertyType.Binary));
                var view = new EWS.ItemView(100)
                {
                    OrderBy     = { { EWS.ItemSchema.DateTimeReceived, EWS.SortDirection.Ascending } },
                    PropertySet = propertySet
                };

                var emails = (from item in service.FindItems(inboxFolderId, view)
                              let email = item as EWS.EmailMessage
                                          where email != null
                                          select email).ToList();

                if (emails.Count > 0)
                {
                    propertySet.Add(EWS.ItemSchema.MimeContent);
                    service.LoadPropertiesForItems(emails, propertySet);
                }
                return(emails.ConvertAll(email => {
                    if (email.ItemClass == "IPM.Note.SMIME")
                    {
                        using (var memoryStream = new MemoryStream(email.MimeContent.Content))
                        {
                            memoryStream.Position = 0L;
                            var pkcs7Mime = (ApplicationPkcs7Mime)MimeEntity.Load(memoryStream);
                            CryptographyContext.Register(typeof(WindowsSecureMimeContext));
                            pkcs7Mime.Verify(out var mimeEntity);
                            var multipart = (Multipart)mimeEntity;
                            var body = multipart.OfType <TextPart>().FirstOrDefault()?.Text;
                            var message = multipart.OfType <TnefPart>().FirstOrDefault()?.ConvertToMessage();
                            return new EmailMessage(
                                email,
                                body,
                                message?.Attachments
                                .OfType <MimePart>()
                                .Select(mp => {
                                memoryStream.SetLength(0L);
                                using (var contentStream = mp.Content.Open())
                                {
                                    contentStream.CopyTo(memoryStream);
                                }
                                return new FileAttachment(
                                    mp.FileName,
                                    memoryStream.ToArray());
                            })
                                .ToArray());
                        }
                    }
                    else
                    {
                        return (IEmailMessage) new EmailMessage(email);
                    }
                }));
            }

            var retries = 0;

            while (true)
            {
                try
                {
                    return(GetEmails());
                }
                catch when(retries < settings.Retries)
                {
                    //await Task.Delay(settings.RetryDelay, cancellationToken);
                    retries++;
                }
            }
        }
Example #37
0
        protected override void ProcessRecord()
        {
            ItemView itemView = new ItemView(30);

            if (this.CustomProperty != null)
            {
                PropertySet propertySet = new PropertySet(BasePropertySet.FirstClassProperties);

                foreach (PropertyDefinitionBase customProp in this.CustomProperty)
                    propertySet.Add(customProp);

                itemView.PropertySet = propertySet;
            }

            EwsItem ewsItems = new EwsItem(this.EwsSession, this.FolderRoot, itemView, this.SearchFilter);
            ewsItems.SearchResultFound += OnSearchResultFound;
            ewsItems.FindItem(this.FolderRoot);
        }
        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);
        }
Example #39
0
        /// <summary>
        /// Obtains a grouped list of items by searching the contents of this folder. Calling this method results in a call to EWS.
        /// </summary>
        /// <param name="searchFilter">The search filter. Available search filter classes
        /// include SearchFilter.IsEqualTo, SearchFilter.ContainsSubstring and
        /// SearchFilter.SearchFilterCollection</param>
        /// <param name="view">The view controlling the number of items returned.</param>
        /// <param name="groupBy">The grouping criteria.</param>
        /// <returns>A collection of grouped items representing the contents of this folder.</returns>
        public async Task <GroupedFindItemsResults <Item> > FindItems(SearchFilter searchFilter, ItemView view, Grouping groupBy)
        {
            EwsUtilities.ValidateParam(groupBy, "groupBy");
            EwsUtilities.ValidateParamAllowNull(searchFilter, "searchFilter");

            ServiceResponseCollection <FindItemResponse <Item> > responses = await this.InternalFindItems <Item>(
                searchFilter,
                view,
                groupBy).ConfigureAwait(false);

            return(responses[0].GroupedFindResults);
        }
Example #40
0
        /// <summary>
        /// Obtains a grouped list of items by searching the contents of this folder. Calling this method results in a call to EWS.
        /// </summary>
        /// <param name="queryString">query string to be used for indexed search</param>
        /// <param name="view">The view controlling the number of items returned.</param>
        /// <param name="groupBy">The grouping criteria.</param>
        /// <returns>A collection of grouped items representing the contents of this folder.</returns>
        public async Task <GroupedFindItemsResults <Item> > FindItems(string queryString, ItemView view, Grouping groupBy)
        {
            EwsUtilities.ValidateParam(groupBy, "groupBy");

            ServiceResponseCollection <FindItemResponse <Item> > responses = await this.InternalFindItems <Item>(queryString, view, groupBy).ConfigureAwait(false);

            return(responses[0].GroupedFindResults);
        }
Example #41
0
        public IEnumerable <IRemoteItem> EnumerateChangesOld(SyncContext context)
        {
            base.EnumerateChanges(context);
            var result  = new List <IRemoteItem>();
            var folders = new List <Exchange.Folder>();

            if (UserSettings.LoadAll)
            {
                Exchange.Folder rootFolder = Exchange.Folder.Bind(Service, Exchange.WellKnownFolderName.MsgFolderRoot);
                var             filter     = new Exchange.SearchFilter.IsEqualTo(
                    Exchange.FolderSchema.FolderClass, ExchangeConsts.NoteFolderClassName);
                folders.GetAllFoldersByFilter(rootFolder, filter);
            }
            else
            {
                folders = SafeBindFolders(Service, UserSettings.RemoteFolderUIds.Keys, context);
            }
            var itemsFilterCollection = new Exchange.SearchFilter.SearchFilterCollection(Exchange.LogicalOperator.And);
            var draftFilter           = new Exchange.SearchFilter.IsNotEqualTo(Exchange.ItemSchema.IsDraft, true);

            itemsFilterCollection.Add(draftFilter);
            DateTime loadEmailsFromDate = LoadEmailsFromDate != DateTime.MinValue
                                ? LoadEmailsFromDate
                                : UserSettings.LastSyncDate;

            if (loadEmailsFromDate != DateTime.MinValue)
            {
                var localLastSyncDate = GetLastSyncDate(loadEmailsFromDate);
                var itemsFilter       = new Exchange.SearchFilter.IsGreaterThan(Exchange.ItemSchema.LastModifiedTime,
                                                                                localLastSyncDate);
                _itemsFilterCollection.Add(itemsFilter);
            }
            FilterDeprecatedFolders(ref folders);
            foreach (var noteFolder in folders)
            {
                var activityFolderIds = new List <Guid>();
                if (UserSettings.RootFolderId != Guid.Empty)
                {
                    activityFolderIds.Add(UserSettings.RootFolderId);
                }
                var folderId = GetFolderId(noteFolder);
                if (UserSettings.RemoteFolderUIds.ContainsKey(folderId))
                {
                    activityFolderIds.Add(UserSettings.RemoteFolderUIds[folderId]);
                }
                Exchange.PropertySet idOnlyPropertySet = new Exchange.PropertySet(Exchange.BasePropertySet.IdOnly);
                var itemView = new Exchange.ItemView(PageItemCount)
                {
                    PropertySet = idOnlyPropertySet
                };
                Exchange.FindItemsResults <Exchange.Item> itemCollection;
                do
                {
                    itemCollection = GetFolderItemsByFilter(noteFolder, itemsFilterCollection, itemView);
                    if (itemCollection == null)
                    {
                        break;
                    }
                    result.AddRange(GetEmailsFromCollection(itemCollection, activityFolderIds));
                } while (itemCollection.MoreAvailable);
            }
            return(result);
        }
Example #42
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();
        }
Example #43
0
        /// <summary>
        /// In the specified directory <paramref name="folder"/>, finds all items <see cref="Exchange.Item"/>,
        /// that match the filter <paramref name="filter"/>, and returns them collection. In the object
        /// <paramref name="view"/> fixed number of read items in the catalog.
        /// </summary>
        /// <param name="folder">Exchange folder.</param>
        /// <param name="filter">Search filter.</param>
        /// <param name="view">Settings view in the directory search operation.</param>
        /// <returns>Items collection<see cref="Exchange.Item"/>.
        /// </returns>
        public static Exchange.FindItemsResults <Exchange.Item> ReadItems(this Exchange.Folder folder,
                                                                          Exchange.SearchFilter filter, Exchange.ItemView view)
        {
            Exchange.FindItemsResults <Exchange.Item> result =
                filter == null?folder.FindItems(view) : folder.FindItems(filter, view);

            view.Offset = result.NextPageOffset ?? 0;
            return(result);
        }
Example #44
0
        /// <summary>
        /// <see cref="ExchangeSyncProvider.EnumerateChanges"/>
        /// </summary>
        public override IEnumerable <IRemoteItem> EnumerateChanges(SyncContext context)
        {
            base.EnumerateChanges(context);
            var result = new List <IRemoteItem>();

            if (!UserSettings.ImportContacts)
            {
                return(result);
            }
            var folders = new List <Exchange.Folder>();

            if (UserSettings.ImportContactsAll)
            {
                Exchange.Folder rootFolder = Exchange.Folder.Bind(Service, Exchange.WellKnownFolderName.MsgFolderRoot);
                var             filter     = new Exchange.SearchFilter.IsEqualTo(
                    Exchange.FolderSchema.FolderClass, ExchangeConsts.ContactFolderClassName);
                folders.GetAllFoldersByFilter(rootFolder, filter);
            }
            else
            {
                folders = SafeBindFolders(Service, UserSettings.RemoteFolderUIds.Keys, context);
            }
            Exchange.SearchFilter itemsFilter = GetExternalItemsFiltersHandler != null
                                        ? GetExternalItemsFiltersHandler() as Exchange.SearchFilter
                                        : GetContactsFilters();

            SyncItemSchema schema = FindSchemaBySyncValueName(typeof(ExchangeContact).Name);
            var            exchangeAddrDetails = new List <ExchangeAddressDetail>();
            var            exchangeCompanies   = new List <string>();

            foreach (Exchange.Folder noteFolder in folders)
            {
                var itemView = new Exchange.ItemView(PageItemCount);
                Exchange.FindItemsResults <Exchange.Item> itemCollection;
                do
                {
                    itemCollection = noteFolder.ReadItems(itemsFilter, itemView);
                    foreach (Exchange.Item item in itemCollection)
                    {
                        Exchange.Contact fullContact = GetFullItemHandler != null
                                                                ? GetFullItemHandler(item.Id.UniqueId) as Exchange.Contact
                                                                : GetFullContact(item.Id);

                        if (fullContact == null)
                        {
                            continue;
                        }
                        var remoteItem = new ExchangeContact(schema, fullContact, TimeZone);
                        remoteItem.InitIdProperty(context);
                        result.Add(remoteItem);
                        if (!string.IsNullOrEmpty(fullContact.CompanyName))
                        {
                            exchangeCompanies.Add(fullContact.CompanyName);
                        }
                        AddAddressDetails(exchangeAddrDetails, fullContact);
                    }
                } while (itemCollection.MoreAvailable);
            }
            FillAddressDetailsData(context, exchangeAddrDetails);
            FillAccountsMap(context, exchangeCompanies.Distinct().ToList());
            return(result);
        }
        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;
        }