/// <summary>
        /// Проверяет успешность подключения к серверу Exchange с указанными параметрами
        /// </summary>
        /// <param name="ex">Параметры подключения</param>
        /// <param name="message">Возвращает текст ошибки подключения при ее наличии</param>
        /// <returns></returns>
        public static bool CheckConnection(Configuration.Exchange ex, out string message)
        {
            try {
                message = string.Empty;

                ExchangeServiceBinding bind = new ExchangeServiceBinding();
                bind.Credentials = new NetworkCredential(ex.Username, ex.Password, ex.Domain);
                bind.Url         = "https://" + ex.ServerName + "/EWS/Exchange.asmx";

                FindItemType findType = new FindItemType();
                findType.Traversal           = ItemQueryTraversalType.Shallow;
                findType.ItemShape           = new ItemResponseShapeType();
                findType.ItemShape.BaseShape = DefaultShapeNamesType.IdOnly;

                DistinguishedFolderIdType folder = new DistinguishedFolderIdType();
                folder.Id = DistinguishedFolderIdNameType.inbox;
                findType.ParentFolderIds = new BaseFolderIdType[] { folder };

                FindItemResponseType findResp = bind.FindItem(findType);
            }
            catch (Exception error) {
                message = error.Message;
                return(false);
            }

            return(true);
        }
        private ResponseMessageType[] GetFolderItems(ExchangeServiceBinding svc, DistinguishedFolderIdNameType folder)
        {
            // Form the FindItem request.
            FindItemType findItemRequest = new FindItemType();

            findItemRequest.Traversal = ItemQueryTraversalType.Shallow;

            // Define which item properties are returned in the response.
            ItemResponseShapeType itemProperties = new ItemResponseShapeType();

            itemProperties.BaseShape = DefaultShapeNamesType.AllProperties;

            //Define propriedade que armazena antigo ID
            PathToExtendedFieldType netShowUrlPath = new PathToExtendedFieldType();

            netShowUrlPath.PropertyTag  = "0x3A4D";
            netShowUrlPath.PropertyType = MapiPropertyTypeType.String;

            //Adiciona propriedade na busca
            itemProperties.AdditionalProperties    = new BasePathToElementType[1];
            itemProperties.AdditionalProperties[0] = netShowUrlPath;

            // Add properties shape to the request.
            findItemRequest.ItemShape = itemProperties;

            // Identify which folders to search to find items.
            DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[2];
            folderIDArray[0]    = new DistinguishedFolderIdType();
            folderIDArray[0].Id = folder;

            // Add folders to the request.
            findItemRequest.ParentFolderIds = folderIDArray;

            // Send the request and get the response.
            FindItemResponseType findItemResponse = svc.FindItem(findItemRequest);

            // Get the response messages.
            ResponseMessageType[] rmta = findItemResponse.ResponseMessages.Items;

            return(rmta);
        }
        /// <summary>
        /// Выполняет поиск входящих писем с подтверждением об обработке файлов за указанный период
        /// </summary>
        /// <param name="begin">Дата начиная с которой будет происходить поиск писем</param>
        /// <returns></returns>
        public static ItemType[] GetMessages(DateTime begin)
        {
            ExchangeServiceBinding bind = new ExchangeServiceBinding();

            bind.Credentials = new NetworkCredential(AppHelper.Configuration.Exchange.Username.GetDecryptedString(),
                                                     AppHelper.Configuration.Exchange.Password.GetDecryptedString(), AppHelper.Configuration.Exchange.Domain);
            bind.Url = "https://" + AppHelper.Configuration.Exchange.ServerName + "/EWS/Exchange.asmx";

            FindItemType findType = new FindItemType();

            findType.Traversal           = ItemQueryTraversalType.Shallow;
            findType.ItemShape           = new ItemResponseShapeType();
            findType.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;

            DistinguishedFolderIdType folder = new DistinguishedFolderIdType();

            folder.Id = DistinguishedFolderIdNameType.inbox;
            findType.ParentFolderIds = new BaseFolderIdType[] { folder };

            IsEqualToType            isEq  = new IsEqualToType();
            PathToUnindexedFieldType uPath = new PathToUnindexedFieldType();

            uPath.FieldURI = UnindexedFieldURIType.messageFrom;
            FieldURIOrConstantType constType  = new FieldURIOrConstantType();
            ConstantValueType      constValue = new ConstantValueType();

            constValue.Value        = AppHelper.Configuration.Exchange.SenderName;
            constType.Item          = constValue;
            isEq.Item               = uPath;
            isEq.FieldURIOrConstant = constType;

            IsGreaterThanOrEqualToType isGrEq = new IsGreaterThanOrEqualToType();
            PathToUnindexedFieldType   uPath2 = new PathToUnindexedFieldType();

            uPath2.FieldURI = UnindexedFieldURIType.itemDateTimeSent;
            FieldURIOrConstantType constType2  = new FieldURIOrConstantType();
            ConstantValueType      constValue2 = new ConstantValueType();

            constValue2.Value         = string.Format("{0}-{1}-{2}T00:00:00Z", begin.Year, begin.Month.ToString("D2"), begin.Day.ToString("D2"));
            constType2.Item           = constValue2;
            isGrEq.Item               = uPath2;
            isGrEq.FieldURIOrConstant = constType2;

            AndType and = new AndType();

            and.Items = new SearchExpressionType[] { isEq, isGrEq };

            findType.Restriction      = new RestrictionType();
            findType.Restriction.Item = and;

            FindItemResponseType        findResp = bind.FindItem(findType);
            FindItemResponseMessageType resMes   = findResp.ResponseMessages.Items[0] as FindItemResponseMessageType;

            if (resMes.ResponseClass != ResponseClassType.Success)
            {
                throw new Exception("Ошибка при получении ответа от сервера Exchange:\n" + resMes.MessageText);
            }
            ItemType[] messages = (resMes.RootFolder.Item as ArrayOfRealItemsType).Items;

            return(messages);
        }
Exemple #4
0
        private static void Process(string username, string password, string folderName)
        {
            Console.WriteLine(" > Opening file...");

            var path  = Directory.GetCurrentDirectory() + @"\Leebl.csv";
            var leads = new LeadCollection(path);

            var binding = new ExchangeServiceBinding
            {
                Url         = "https://amxprd0510.outlook.com/ews/exchange.asmx",
                Credentials = new NetworkCredential(username, password),
                RequestServerVersionValue = new RequestServerVersion {
                    Version = ExchangeVersionType.Exchange2010
                }
            };

            #region Get folder

            Console.WriteLine(" > Retrieving folder...");

            var folderRequest = new FindFolderType
            {
                Traversal   = FolderQueryTraversalType.Deep,
                FolderShape = new FolderResponseShapeType {
                    BaseShape = DefaultShapeNamesType.IdOnly
                },
                ParentFolderIds = new BaseFolderIdType[]
                {
                    new DistinguishedFolderIdType {
                        Id = DistinguishedFolderIdNameType.root
                    }
                },
                Restriction = new RestrictionType
                {
                    Item = new ContainsExpressionType
                    {
                        ContainmentMode                = ContainmentModeType.Substring,
                        ContainmentModeSpecified       = true,
                        ContainmentComparison          = ContainmentComparisonType.IgnoreCase,
                        ContainmentComparisonSpecified = true,
                        Item = new PathToUnindexedFieldType
                        {
                            FieldURI = UnindexedFieldURIType.folderDisplayName
                        },
                        Constant = new ConstantValueType
                        {
                            Value = folderName
                        }
                    }
                }
            };

            var folderResponse = binding.FindFolder(folderRequest);
            var folderIds      = new List <BaseFolderIdType>();

            foreach (var folder in folderResponse.ResponseMessages.Items
                     .Select(x => (x as FindFolderResponseMessageType))
                     .Where(x => x != null))
            {
                folderIds.AddRange(folder.RootFolder.Folders.Select(y => y.FolderId));
            }

            #endregion

            #region Get items

            Console.WriteLine(" > Retrieving items...");

            var itemRequest = new FindItemType
            {
                Traversal = ItemQueryTraversalType.Shallow,
                ItemShape = new ItemResponseShapeType {
                    BaseShape = DefaultShapeNamesType.Default
                },
                ParentFolderIds = folderIds.ToArray()
            };

            var itemResponse = binding.FindItem(itemRequest);
            var itemIds      = new List <BaseItemIdType>();

            foreach (var item in itemResponse.ResponseMessages.Items
                     .Select(x => (x as FindItemResponseMessageType))
                     .Where(x => x != null)
                     .Where(x => x.RootFolder != null && x.RootFolder.TotalItemsInView > 0))
            {
                itemIds.AddRange(((ArrayOfRealItemsType)item.RootFolder.Item).Items.Select(y => y.ItemId));
            }

            #endregion

            #region Get bodies

            Console.WriteLine(" > Parsing " + itemIds.Count + " messages...");

            var messageRequest = new GetItemType
            {
                ItemShape = new ItemResponseShapeType {
                    BaseShape = DefaultShapeNamesType.AllProperties
                },
                ItemIds = itemIds.ToArray()
            };

            var messageResponse = binding.GetItem(messageRequest);

            foreach (var message in messageResponse.ResponseMessages.Items
                     .Select(x => (x as ItemInfoResponseMessageType))
                     .Where(x => x != null)
                     .Select(x => x.Items.Items[0])
                     .Where(x => x != null))
            {
                leads.Add(message.Body.Value, message.DateTimeSent);
            }

            #endregion

            Console.WriteLine(" > Saving to file...");
            leads.Save(path);
        }
Exemple #5
0
        public static void ProcessMails()
        {
            var regex = new Regex("SQL Server Job System: '(.*?) (.*?)' completed on (.*?)$");

            var binding = new ExchangeServiceBinding
            {
                Url         = "https://amxprd0510.outlook.com/ews/exchange.asmx",
                Credentials = new NetworkCredential("*****@*****.**", ""),
                RequestServerVersionValue = new RequestServerVersion {
                    Version = ExchangeVersionType.Exchange2010
                }
            };

            var request = new FindItemType
            {
                Traversal = ItemQueryTraversalType.Shallow,
                ItemShape = new ItemResponseShapeType {
                    BaseShape = DefaultShapeNamesType.Default
                },
                ParentFolderIds = new BaseFolderIdType[]
                {
                    new DistinguishedFolderIdType {
                        Id = DistinguishedFolderIdNameType.inbox
                    }
                }
            };

            var response = binding.FindItem(request);
            var toDelete = new List <ItemIdType>();

            foreach (FindItemResponseMessageType message in response.ResponseMessages.Items)
            {
                if (message.RootFolder == null || message.RootFolder.TotalItemsInView <= 0)
                {
                    continue;
                }
                foreach (var item in ((ArrayOfRealItemsType)message.RootFolder.Item).Items)
                {
                    if (!regex.IsMatch(item.Subject))
                    {
                        continue;
                    }
                    var matches = regex.Matches(item.Subject);

                    toDelete.Add(item.ItemId);

                    var applicationID = "BI";
                    var customerID    = matches[0].Groups[1].Value.Replace('_', ' ');
                    var processID     = matches[0].Groups[2].Value.Replace('_', ' ');
                    var groupID       = matches[0].Groups[3].Value.Replace("\\", "");

                    // for BI, the subject of an email message should be as follows:
                    // SQL Server Job System: '<Customer> <Process>' completed on <Groupname>
                    // or, SQL Server Job System: '<Customer> BI-<Process>' completed on <Groupname>

                    // however, Groupname is always ignored for BI jobs

                    if (processID.StartsWith("BI-"))
                    {
                        applicationID = "BI";
                        processID     = processID.Substring(3);
                    }

                    // for DBA, the subject of an email message should be as follows:
                    // SQL Server Job System: '<Customer> DBA-<Process>' completed on <Groupname>

                    // the Groupname will always be appended to the process name, so that process will be <Process @ Groupname>

                    if (processID.StartsWith("DBA-"))
                    {
                        applicationID = "DBA";
                        processID     = processID.Substring(4);
                        processID     = string.Format("{0} @ {1}", processID, groupID);
                    }

                    string msg;
                    if (!Client.Service.Update(out msg, Methods.GetUrl("Service.asmx"), applicationID, customerID, processID))
                    {
                        throw new Exception(msg);
                    }
                }
            }

            if (toDelete.Count == 0)
            {
                return;
            }

            binding.DeleteItem(new DeleteItemType
            {
                DeleteType = DisposalType.MoveToDeletedItems,
                ItemIds    = toDelete.ToArray()
            });
        }
Exemple #6
0
        private static void Process(string username, string password, string folder, string to)
        {
            Console.WriteLine("\r\n  Processing...\r\n");
            Console.WriteLine("  > Connecting...");

            var binding = new ExchangeServiceBinding
            {
                Url         = "https://amxprd0510.outlook.com/ews/exchange.asmx",
                Credentials = new NetworkCredential(username, password),
                RequestServerVersionValue = new RequestServerVersion {
                    Version = ExchangeVersionType.Exchange2010
                }
            };

            #region Get folder

            Console.WriteLine("  > Retrieving folder...");

            var folderId = binding.FindFolder(new FindFolderType
            {
                Traversal   = FolderQueryTraversalType.Deep,
                FolderShape = new FolderResponseShapeType {
                    BaseShape = DefaultShapeNamesType.IdOnly
                },
                ParentFolderIds = new BaseFolderIdType[] { new DistinguishedFolderIdType {
                                                               Id = DistinguishedFolderIdNameType.root
                                                           } },
                Restriction = new RestrictionType
                {
                    Item = new ContainsExpressionType
                    {
                        ContainmentMode                = ContainmentModeType.Substring,
                        ContainmentModeSpecified       = true,
                        ContainmentComparison          = ContainmentComparisonType.IgnoreCase,
                        ContainmentComparisonSpecified = true,
                        Item = new PathToUnindexedFieldType {
                            FieldURI = UnindexedFieldURIType.folderDisplayName
                        },
                        Constant = new ConstantValueType {
                            Value = folder
                        }
                    }
                }
            })
                           .ResponseMessages.Items.OfType <FindFolderResponseMessageType>()
                           .First().RootFolder.Folders.First().FolderId;

            #endregion

            #region Get items

            Console.WriteLine("  > Retrieving items...");

            var itemIds = binding.FindItem(new FindItemType
            {
                Traversal = ItemQueryTraversalType.Shallow,
                ItemShape = new ItemResponseShapeType {
                    BaseShape = DefaultShapeNamesType.Default
                },
                ParentFolderIds = new BaseFolderIdType[] { new DistinguishedFolderIdType {
                                                               Id = DistinguishedFolderIdNameType.inbox
                                                           } }
            })
                          .ResponseMessages.Items.Select(x => x as FindItemResponseMessageType).Where(x => x != null)
                          .Where(x => x.RootFolder != null && x.RootFolder.TotalItemsInView > 0)
                          .SelectMany(item => ((ArrayOfRealItemsType)item.RootFolder.Item).Items.Select(y => y.ItemId))
                          .ToArray();

            var messages = binding.GetItem(new GetItemType {
                ItemShape = new ItemResponseShapeType {
                    BaseShape = DefaultShapeNamesType.AllProperties
                }, ItemIds = itemIds
            })
                           .ResponseMessages.Items.Select(x => x as ItemInfoResponseMessageType).Where(x => x != null)
                           .Select(x => x.Items.Items[0] as MessageType).Where(x => x != null && x.IsFromMe)
                           .ToList();

            #endregion

            #region Process items

            if (!messages.Any())
            {
                Console.WriteLine("  > No messages to process!");
                return;
            }

            Console.WriteLine("  > Processing " + messages.Count + " messages...\r\n");

            foreach (var message in messages)
            {
                Console.WriteLine("    " + message.Subject);

                // forward message
                binding.CreateItem(new CreateItemType
                {
                    MessageDisposition          = MessageDispositionType.SendAndSaveCopy,
                    MessageDispositionSpecified = true,
                    SavedItemFolderId           = new TargetFolderIdType {
                        Item = new DistinguishedFolderIdType {
                            Id = DistinguishedFolderIdNameType.sentitems
                        }
                    },
                    Items = new NonEmptyArrayOfAllItemsType
                    {
                        Items = new ItemType[]
                        {
                            new ForwardItemType
                            {
                                Subject      = "[VERK]",
                                ToRecipients = new[] { new EmailAddressType {
                                                           EmailAddress = to
                                                       } },
                                ReferenceItemId = new ItemIdType {
                                    ChangeKey = message.ItemId.ChangeKey, Id = message.ItemId.Id
                                },
                                NewBodyContent = new BodyType {
                                    BodyType1 = BodyTypeType.HTML, Value = "Email is automatically forwarded by HENK."
                                }
                            }
                        }
                    }
                });

                // move to subfolder
                binding.MoveItem(new MoveItemType
                {
                    ToFolderId = new TargetFolderIdType {
                        Item = folderId
                    },
                    ItemIds = new BaseItemIdType[] { message.ItemId }
                });
            }

            Console.WriteLine("\r\n  Finished!");

            #endregion
        }