Пример #1
0
        public bool ApplyCredentialsToExchangeService(EWS.ExchangeService Exchange)
        {
            if (!HaveValidCredentials())
            {
                return(false);
            }

            switch (_authType)
            {
            case AuthType.Default:
                Exchange.UseDefaultCredentials = true;
                return(true);

            case AuthType.Basic:
                Exchange.Credentials = new NetworkCredential(Username, _password);
                return(true);

            case AuthType.Certificate:
                //Request.ClientCertificates = new X509CertificateCollection();
                //Request.ClientCertificates.Add(_certificate);
                return(false);

            case AuthType.OAuth:
                Exchange.Credentials = new EWS.OAuthCredentials(_lastOAuthResult.AccessToken);
                return(true);
            }

            return(false);
        }
        public static FolderId FindFolder(Microsoft.Exchange.WebServices.Data.ExchangeService service)
        {
            var resultid     = new FolderId("0");
            var responseview = new FolderView(1);
            var filter       = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "sync-adressen");

            var folderresponse = service.FindFolders(WellKnownFolderName.PublicFoldersRoot, filter, responseview);

            if (folderresponse.Count() == 1)
            {
                var responseview2   = new FolderView(1);
                var filter2         = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "sync-contacten");
                var folderresponse2 = service.FindFolders(folderresponse.First().Id, filter2, responseview2);
                if (folderresponse2.Count() == 1)
                {
                    var responseview3   = new FolderView(1);
                    var filter3         = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "syncContacts");
                    var folderresponse3 = service.FindFolders(folderresponse2.First().Id, filter3, responseview3);
                    if (folderresponse3.Count() == 1)
                    {
                        resultid = folderresponse3.First().Id;
                    }
                }
            }
            return(resultid);
        }
Пример #3
0
        public void StreamingExchange()
        {
            try
            {
                Stopwatch watch;
                long elapsedMs = 0;

                watch = Stopwatch.StartNew();

                _logger.LogInformation(string.Format(LogsProcess.InitProcess, Variables.StreamingExchange, DateTime.Now.ToString()));

                Exchange.ExchangeService service = new Exchange.ExchangeService(Exchange.ExchangeVersion.Exchange2013);
                Exchange.WebCredentials wbcred = new Exchange.WebCredentials(
                    _parametersProcessum.GeracaoArquivoEmail.Login,
                    _parametersProcessum.GeracaoArquivoEmail.Senha);

                service.Credentials = wbcred;
                service.AutodiscoverUrl(_parametersProcessum.GeracaoArquivoEmail.Login, EWSConnection.RedirectionUrlValidationCallback);

                EWSConnection.SetStreamingNotifications(service, resetEvent, _parametersProcessum);

                resetEvent.WaitOne();

                watch.Stop();

                elapsedMs = watch.ElapsedMilliseconds;

                _logger.LogInformation(string.Format(LogsProcess.FinishProcess, Variables.StreamingExchange, DateTime.Now.ToString()));
                _logger.LogInformation(string.Format(LogsProcess.TimeExecution, Variables.StreamingExchange, elapsedMs.ToString()));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static void MakePublicContactsFolder(Microsoft.Exchange.WebServices.Data.ExchangeService service)
        {
            var folder = new ContactsFolder(service);

            folder.DisplayName = "ZeebregtsCs";
            folder.Save(WellKnownFolderName.Contacts);
        }
        public static void DeleteContact(Microsoft.Exchange.WebServices.Data.ExchangeService service, ItemId contactUniId)
        {
            Console.WriteLine("Deleting contact");
            Contact contact = Contact.Bind(service, contactUniId);

            contact.Delete(DeleteMode.MoveToDeletedItems);
        }
        public static void MakeFolder(Microsoft.Exchange.WebServices.Data.ExchangeService service)
        {
            ContactsFolder folder = new ContactsFolder(service);

            folder.DisplayName = "syncContacts";
            folder.Save(FindFolder(service));
        }
    /// <summary>
    /// send to multi receiver
    /// Send email with CC and BCC and file
    /// </summary>
    /// <param name="receiver"></param>
    /// <param name="subject"></param>
    /// <param name="message"></param>
    /// <param name="cc"></param>
    /// <param name="bcc"></param>
    /// <param name="filename"></param>
    /// <returns></returns>
    ///

    public void sendExchangeEmail()
    {
        try
        {
            Microsoft.Exchange.WebServices.Data.ExchangeService service = new Microsoft.Exchange.WebServices.Data.ExchangeService();
            service.Credentials = new Microsoft.Exchange.WebServices.Data.WebCredentials("*****@*****.**", "Hcllp@2009~", "mail.harshwal.com");
            service.Url         = new Uri("https://mail.harshwal.com/EWS/Exchange.asmx");
            // Set the URL.
            //service.AutodiscoverUrl("*****@*****.**");

            Microsoft.Exchange.WebServices.Data.EmailMessage message = new Microsoft.Exchange.WebServices.Data.EmailMessage(service);

            // Add properties to the email message.
            message.Subject = "Interesting";
            message.Body    = "The merger is finalized.";
            message.ToRecipients.Add("*****@*****.**");

            // Send the email message and save a copy.
            message.SendAndSaveCopy();
        }

        catch (Exception ex)
        {
        }
    }
Пример #8
0
        public List <ExchangeMailFolder> GetMailboxFolders(string mailServerId, string mailboxName,
                                                           string mailboxPassword, string senderEmailAddress, string folderClassName)
        {
            if (string.IsNullOrEmpty(mailboxPassword))
            {
                mailboxPassword = GetExistingMailboxPassword(senderEmailAddress, UserConnection);
            }
            var credentials = new Mail.Credentials {
                UserName     = mailboxName,
                UserPassword = mailboxPassword,
                ServerId     = Guid.Parse(mailServerId),
                UseOAuth     = GetSettingsHasOauth(senderEmailAddress, UserConnection)
            };

            SetServerCertificateValidation();
            var exchangeUtility = new ExchangeUtilityImpl();

            Exchange.ExchangeService service = exchangeUtility.CreateExchangeService(UserConnection, credentials,
                                                                                     senderEmailAddress, true);
            var filterCollection = new Exchange.SearchFilter.SearchFilterCollection(Exchange.LogicalOperator.Or);
            var filter           = new Exchange.SearchFilter.IsEqualTo(Exchange.FolderSchema.FolderClass, folderClassName);
            var nullfilter       = new Exchange.SearchFilter.Exists(Exchange.FolderSchema.FolderClass);

            filterCollection.Add(filter);
            filterCollection.Add(new Exchange.SearchFilter.Not(nullfilter));
            string[] selectedFolders = null;
            var      idPropertySet   = new Exchange.PropertySet(Exchange.BasePropertySet.IdOnly);

            Exchange.Folder draftFolder = null;
            if (folderClassName == ExchangeConsts.NoteFolderClassName)
            {
                Exchange.Folder inboxFolder = Exchange.Folder.Bind(service, Exchange.WellKnownFolderName.Inbox,
                                                                   idPropertySet);
                if (inboxFolder != null)
                {
                    selectedFolders = new[] { inboxFolder.Id.UniqueId };
                }
                draftFolder = Exchange.Folder.Bind(service, Exchange.WellKnownFolderName.Drafts, idPropertySet);
            }
            List <ExchangeMailFolder> folders = exchangeUtility.GetHierarhicalFolderList(service,
                                                                                         Exchange.WellKnownFolderName.MsgFolderRoot, filterCollection, selectedFolders);

            if (folders != null && folders.Any())
            {
                folders[0] = new ExchangeMailFolder {
                    Id       = folders[0].Id,
                    Name     = mailboxName,
                    ParentId = string.Empty,
                    Path     = string.Empty,
                    Selected = false
                };
                if (draftFolder != null)
                {
                    folders.Remove(folders.FirstOrDefault(e => e.Path == draftFolder.Id.UniqueId));
                }
            }
            return(folders);
        }
Пример #9
0
 public ExchangeService CreateExchangeService()
 {
     ServicePointManager.ServerCertificateValidationCallback = this.CertificateValidationCallBack;
     Microsoft.Exchange.WebServices.Data.ExchangeService service = new Microsoft.Exchange.WebServices.Data.ExchangeService();
     service.Credentials = new Microsoft.Exchange.WebServices.Data.WebCredentials(EmailProperties.GetInstance.ExchangeMailServerUsername, EmailProperties.GetInstance.ExchangeMailServerPassword);
     service.Url         = new Uri(EmailProperties.GetInstance.ExchangeUriService);
     service.Timeout     = EmailProperties.GetInstance.ExchangeConnectionTimeout;
     return(service);
 }
        public static void SendEmail(Microsoft.Exchange.WebServices.Data.ExchangeService service)
        {
            EmailMessage email = new EmailMessage(service);

            email.ToRecipients.Add("*****@*****.**");
            email.Subject = "HelloWorld";
            email.Body    = new MessageBody("This is the first email I've sent by using the EWS Managed API.");
            email.Send();
        }
    private static void GetAllFolders(Exchange.ExchangeService Service, string LogFilePath)
    {
        Exchange.ExtendedPropertyDefinition oIsHidden = default(Exchange.ExtendedPropertyDefinition);
        List <Exchange.Folder> oFolders = default(List <Exchange.Folder>);

        Exchange.FindFoldersResults oResults = default(Exchange.FindFoldersResults);
        bool lHasMore = false;

        Exchange.Folder     oChild = default(Exchange.Folder);
        Exchange.FolderView oView  = default(Exchange.FolderView);
        short         nPageSize    = 0;
        short         nOffSet      = 0;
        List <string> oPaths       = default(List <string>);
        List <string> oPath        = default(List <string>);

        oIsHidden = new Exchange.ExtendedPropertyDefinition(0x10f4, Exchange.MapiPropertyType.Boolean);
        nPageSize = 1000;
        oFolders  = new List <Exchange.Folder>();
        lHasMore  = true;
        nOffSet   = 0;
        while (lHasMore)
        {
            oView             = new Exchange.FolderView(nPageSize, nOffSet, Exchange.OffsetBasePoint.Beginning);
            oView.PropertySet = new Exchange.PropertySet(Exchange.BasePropertySet.IdOnly);
            oView.PropertySet.Add(oIsHidden);
            oView.PropertySet.Add(Exchange.FolderSchema.ParentFolderId);
            oView.PropertySet.Add(Exchange.FolderSchema.DisplayName);
            oView.PropertySet.Add(Exchange.FolderSchema.FolderClass);
            oView.PropertySet.Add(Exchange.FolderSchema.TotalCount);
            oView.Traversal = Exchange.FolderTraversal.Deep;
            oResults        = Service.FindFolders(Exchange.WellKnownFolderName.MsgFolderRoot, oView);
            oFolders.AddRange(oResults.Folders);
            lHasMore = oResults.MoreAvailable;
            if (lHasMore)
            {
                nOffSet += nPageSize;
            }
        }
        oFolders.RemoveAll(Folder => Folder.ExtendedProperties(0).Value == true);
        oFolders.RemoveAll(Folder => Folder.FolderClass != "IPF.Note");
        oPaths = new List <string>();
        oFolders.ForEach(Folder =>
        {
            oChild = Folder;
            oPath  = new List <string>();
            do
            {
                oPath.Add(oChild.DisplayName);
                oChild = oFolders.SingleOrDefault(Parent => Parent.Id.UniqueId == oChild.ParentFolderId.UniqueId);
            } while (oChild != null);
            oPath.Reverse();
            oPaths.Add("{0}{1}{2}".ToFormat(Strings.Join(oPath.ToArray, DELIMITER), Constants.vbTab, Folder.TotalCount));
        });
        oPaths.RemoveAll(Path => Path.StartsWith("Sync Issues"));
        File.WriteAllText(LogFilePath, Strings.Join(oPaths.ToArray, Constants.vbCrLf));
    }
Пример #12
0
 /// <summary>TBD</summary>
 /// <returns>TBD</returns>
 public static ExchangeService GetService()
 {
     Microsoft.Exchange.WebServices.Data.ExchangeService service = new Microsoft.Exchange.WebServices.Data.ExchangeService();
     service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SID, ((System.Security.Principal.WindowsIdentity)HttpContext.Current.User.Identity).User.Value);
     //service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "*****@*****.**");
     //service.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
     service.Credentials = new WebCredentials("crmExchangeMgr", "St3v13rayv", "titanoutdoor");
     service.AutodiscoverUrl(Security.GetUserEmailFromId(Security.GetCurrentUserId));
     return service;
 }
Пример #13
0
        /// <summary>
        /// Sets <see cref="ExchangeClient.Service"/> property value.
        /// </summary>
        /// <param name="bpmEmailMessage">Email message instance.</param>
        /// <param name="ignoreRights">Ignore rights when data requested flag.</param>
        private void SetServiceConnection(EmailMessage bpmEmailMessage, bool ignoreRights)
        {
            string emailAddress = bpmEmailMessage.From.ExtractEmailAddress();

            if (Service == null)
            {
                Service = _credentials != null
                                        ? _exchangeUtility.CreateExchangeService(_userConnection, _credentials, emailAddress)
                                        : _exchangeUtility.CreateExchangeService(_userConnection, emailAddress, false, ignoreRights);
            }
        }
        /// <summary>
        /// Attempts to get Id of Conflicts folder
        /// If the value can not be obtained, the method returns <c>null</c>.</summary>
        /// <param name="exchangeService">Exchange service.</param>
        /// <returns>Id of this folder, or <c>null</c>.</returns>
        public Exchange.FolderId GetConflictsFolderId(Exchange.ExchangeService exchangeService)
        {
            var rootFolderId = Exchange.Folder.Bind(exchangeService, Exchange.WellKnownFolderName.MsgFolderRoot).Id;

            Exchange.FolderId syncIssuesFolderId = GetChildIdByName(exchangeService, rootFolderId, "Sync Issues");
            if (syncIssuesFolderId == null)
            {
                return(null);
            }
            return(GetChildIdByName(exchangeService, syncIssuesFolderId, "Conflicts"));
        }
        public static Microsoft.Exchange.WebServices.Data.ExchangeService GetNewServiceHook()
        {
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

            Microsoft.Exchange.WebServices.Data.ExchangeService service = new Microsoft.Exchange.WebServices.Data.ExchangeService(ExchangeVersion.Exchange2013_SP1);
            service.Credentials           = new WebCredentials("*****@*****.**", "Pallas18#2015");
            service.UseDefaultCredentials = false;

            service.TraceEnabled = false;
            service.Url          = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
            return(service);
        }
        private static Exchange.ExchangeService CreateExchangeService(UserConnection userConnection, string mailboxName)
        {
            string serverAddress;
            var    exchangeUtility = GetExchangeUtility();
            var    credentials     = exchangeUtility.GetCredentials(userConnection, mailboxName);

            serverAddress = GetServerAddressByMailbox(userConnection, mailboxName);
            Exchange.ExchangeService exchangeService = new Exchange.ExchangeService(Exchange.ExchangeVersion.Exchange2010_SP1);
            exchangeService.Url         = new Uri(string.Format("https://{0}/EWS/Exchange.asmx", serverAddress));
            exchangeService.Credentials = new Exchange.WebCredentials(credentials.UserName, credentials.UserPassword);
            return(exchangeService);
        }
        public static void MakeNewContact(Microsoft.Exchange.WebServices.Data.ExchangeService service, ExchangeContactItem contactinfo)
        {
            var     f_id    = FindFolder(service);
            Contact contact = new Contact(service);

            Console.WriteLine("Making new contact: " + contactinfo.Achternaam + "," + contactinfo.Voornaam);
            // Specify the name and how the contact should be filed.
            contact.GivenName     = String.IsNullOrEmpty(contactinfo.Voornaam) == false ? contactinfo.Voornaam : "";
            contact.MiddleName    = String.IsNullOrEmpty(contactinfo.Tussenvoegsel) == false ? contactinfo.Tussenvoegsel : "";
            contact.Surname       = String.IsNullOrEmpty(contactinfo.Achternaam) == false ? contactinfo.Achternaam : "";
            contact.FileAsMapping = FileAsMapping.SurnameCommaGivenName;

            // Specify the company name.
            contact.CompanyName = String.IsNullOrEmpty(contactinfo.BedrijfNaam) == false ? contactinfo.BedrijfNaam : "";

            // Specify the business, home, and car phone numbers.
            var phone1type = PhoneNumberKey.PrimaryPhone;
            var phone2type = PhoneNumberKey.MobilePhone;
            var phone3type = PhoneNumberKey.BusinessPhone;

            if (!String.IsNullOrEmpty(contactinfo.TelNrTypes))
            {
                var sets = contactinfo.TelNrTypes.Split(',');
                var nr1  = int.Parse(sets[0].Substring(0, 1));
                var nr2  = int.Parse(sets[1].Substring(0, 1));
                var nr3  = int.Parse(sets[2].Substring(0, 1));
                if (nr2 == nr1)
                {
                    nr2 = 6;
                }
                if (nr3 == nr2 || nr3 == nr1)
                {
                    nr3 = 7;
                }

                phone1type = ConvertTelTypes(nr1);
                phone2type = ConvertTelTypes(nr2);
                phone3type = ConvertTelTypes(nr3);
            }

            contact.PhoneNumbers[phone1type] = String.IsNullOrEmpty(contactinfo.TelNr1) == false ? contactinfo.TelNr1 : "";
            contact.PhoneNumbers[phone2type] = String.IsNullOrEmpty(contactinfo.TelNr2) == false ? contactinfo.TelNr2 : "";
            contact.PhoneNumbers[phone3type] = String.IsNullOrEmpty(contactinfo.TelNr3) == false ? contactinfo.TelNr3 : "";

            // Specify email addresses.
            contact.EmailAddresses[EmailAddressKey.EmailAddress1] = new EmailAddress(String.IsNullOrEmpty(contactinfo.Email1) == false ? contactinfo.Email1 : "*****@*****.**");


            //functie
            contact.JobTitle = String.IsNullOrEmpty(contactinfo.Functie) == false ? contactinfo.Functie : "";
            // Save the contact.
            contact.Save(f_id);
        }
 private Exchange.ExchangeService GetExchangeService()
 {
     Exchange.ExchangeService exchangeService = new Exchange.ExchangeService(Exchange.ExchangeVersion.Exchange2013);
     exchangeService.Url           = new Uri("https://outlook.office365.com/EWS/exchange.asmx");
     exchangeService.TraceListener = new EWSTracer(decodedTokenBox);
     if (checkBoxEWSTraceToOutput.Checked)
     {
         exchangeService.TraceEnabled = true;
         exchangeService.TraceFlags   = Exchange.TraceFlags.All;
     }
     return(exchangeService);
 }
        private void buttonEWSGetInboxCount_Click(object sender, EventArgs e)
        {
            Exchange.ExchangeService exchangeService = GetExchangeService();

            string mbx = textBoxEWSMailbox.Text;

            if (checkBoxEWSImpersonate.Checked)
            {
                if (String.IsNullOrEmpty(mbx))
                {
                    MessageBox.Show("When impersonation is selected, you must specify the mailbox to impersonate");
                    return;
                }
                exchangeService.ImpersonatedUserId = new Exchange.ImpersonatedUserId(Exchange.ConnectingIdType.SmtpAddress, mbx);
            }

            if (tokenBox.Text == string.Empty)
            {
                AcquireDelegateToken();
            }

            try
            {
                exchangeService.Credentials = new Exchange.OAuthCredentials(tokenBox.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("Error: {0}", ex.Message));
                return;
            }

            try
            {
                Exchange.Folder inbox = null;
                if (!String.IsNullOrEmpty(mbx))
                {
                    // Specify the mailbox to access
                    inbox = Exchange.Folder.Bind(exchangeService, new Exchange.FolderId(Exchange.WellKnownFolderName.Inbox, new Exchange.Mailbox(mbx)));
                }
                else
                {
                    // Don't specify the mailbox
                    inbox = Exchange.Folder.Bind(exchangeService, Exchange.WellKnownFolderName.Inbox);
                }

                MessageBox.Show(string.Format("Inbox message count = {0}", inbox.TotalCount.ToString()));
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("Error: {0}", ex.Message));
            }
        }
Пример #20
0
        /// <summary>
        /// Tests <see cref="Exchange.ExchangeService"/> connection.
        /// </summary>
        /// <param name="service"><see cref="Exchange.ExchangeService"/> instance.</param>
        /// <param name="userConnection"><see cref="UserConnection"/> instance.</param>
        /// <param name="senderEmailAddress">Sender email address.</param>
        /// <param name="stopOnFirstError">Stop synchronization triggers on first error flag.</param>
        public static void TestConnection(this Exchange.ExchangeService service, UserConnection userConnection = null,
                                          string senderEmailAddress = "", bool stopOnFirstError = false)
        {
            SynchronizationErrorHelper helper = SynchronizationErrorHelper.GetInstance(userConnection);

            try {
                service.FindFolders(Exchange.WellKnownFolderName.MsgFolderRoot, new Exchange.FolderView(1));
                helper.CleanUpSynchronizationError(senderEmailAddress);
            } catch (Exception ex) {
                helper.ProcessSynchronizationError(senderEmailAddress, ex, stopOnFirstError);
                throw;
            }
        }
        /// <summary>
        /// Returns Id of first child folder by name and root folder id.
        /// If the value can not be obtained, the method returns <c>null</c>.</summary>
        /// <param name="exchangeService">Exchange service.</param>
        /// <param name="parentId">Root folder Id.</param>
        /// <param name="childName">Display name of the finding folder.</param>
        /// <returns>Id of child folder, or <c>null</c>.</returns>
        private Exchange.FolderId GetChildIdByName(Exchange.ExchangeService exchangeService,
                                                   Exchange.FolderId parentId, string childName)
        {
            Exchange.SearchFilter filter = new Exchange.SearchFilter
                                           .IsEqualTo(Exchange.FolderSchema.DisplayName, childName);
            var result = exchangeService.FindFolders(parentId, filter, new Exchange.FolderView(1));

            if (!result.Folders.Any())
            {
                return(null);
            }
            return(result.Folders[0].Id);
        }
Пример #22
0
 //Функция отправки сообщений на Email
 public Task SendEmail(string GetEmail, string mailSubject, string mailBody)
 {
     return(Task.Run(() =>
     {
         Exchange.ExchangeService service = new Exchange.ExchangeService();
         service.Credentials = new NetworkCredential(AppSettings.SendEmail, AppSettings.SendEmailPassword);
         service.AutodiscoverUrl(AppSettings.SendEmail);
         Exchange.EmailMessage emailMessage = new Exchange.EmailMessage(service);
         emailMessage.Body = new Exchange.MessageBody(mailBody);
         emailMessage.ToRecipients.Add(GetEmail);
         emailMessage.Send();
     }));
 }
Пример #23
0
        private ExchangeService GetEwsService()
        {
#pragma warning disable S4423                                                                                                                     // Weak SSL/TLS protocols should not be used
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; //DevSkim: ignore DS440020,DS440000,DS144436
#pragma warning restore S4423                                                                                                                     // Weak SSL/TLS protocols should not be used
            string ewsUrl = RootUrl.AppendPathSegment("EWS/Exchange.asmx");

            var ewsservice = new Microsoft.Exchange.WebServices.Data.ExchangeService
            {
                Credentials = new System.Net.NetworkCredential(Username, Password),
                Url         = new Uri(ewsUrl)
            };
            return(ewsservice);
        }
Пример #24
0
 //Функция отправки сообщений на Email
 public static Task SendEmail(string GetEmail, string itemName)
 {
     return(Task.Run(() =>
     {
         Exchange.ExchangeService service = new Exchange.ExchangeService();
         service.Credentials = new NetworkCredential(AppSettings.SendEmail, AppSettings.SendEmailPassword);
         service.AutodiscoverUrl(AppSettings.SendEmail);
         Exchange.EmailMessage emailMessage = new Exchange.EmailMessage(service);
         emailMessage.Subject = "Аукцион #ProКачка - Вы выиграли приз!";
         emailMessage.Body = new Exchange.MessageBody("Поздравляем, вы выиграли " + itemName + " на нашем аукционе #ProКачка.");
         emailMessage.ToRecipients.Add(GetEmail);
         emailMessage.Send();
     }));
 }
 public static Exchange.ExchangeService ConnectToService(User User, Exchange.ITraceListener Listener)
 {
     Exchange.ExchangeService oService = default(Exchange.ExchangeService);
     oService             = new Exchange.ExchangeService(Exchange.ExchangeVersion.Exchange2013_SP1);
     oService.Credentials = new NetworkCredential(User.EmailAddress, User.Password);
     oService.AutodiscoverUrl(User.EmailAddress, RedirectionUrlValidationCallback);
     if (Listener != null)
     {
         oService.TraceListener = Listener;
         oService.TraceEnabled  = true;
         oService.TraceFlags    = Exchange.TraceFlags.All;
     }
     return(oService);
 }
Пример #26
0
        public List<OutlookAppointment> GetCalendarEntries()
        {
            List<OutlookAppointment> appointments = new List<OutlookAppointment>();
            var _service = new Microsoft.Exchange.WebServices.Data.ExchangeService(Microsoft.Exchange.WebServices.Data.ExchangeVersion.Exchange2010_SP1);
            _service.Credentials = new Microsoft.Exchange.WebServices.Data.WebCredentials(Settings.Instance.ExchageUser, Settings.Instance.ExchagePassword);
            _service.Url = new Uri(Settings.Instance.ExchageServerAddress);
            var items = _service.FindItems(Microsoft.Exchange.WebServices.Data.WellKnownFolderName.Calendar, new Microsoft.Exchange.WebServices.Data.ItemView(int.MaxValue));
            foreach (Microsoft.Exchange.WebServices.Data.Appointment appointment in items)
            {
                OutlookAppointment newAppointment = GetOutlookAppointment(appointment, _service);

                appointments.Add(newAppointment);
            }
            return appointments;
        }
Пример #27
0
        /// <summary>
        /// Binds exchange folders using <paramref name="folderRemoteIds"/>.
        /// </summary>
        /// <param name="service"><see cref="Microsoft.Exchange.WebServices.Data.ExchangeService"/> instance.</param>
        /// <param name="folderRemoteIds">Exchange folders unique identifiers collection.</param>
        /// <returns>Exchange folders collection.</returns>
        private List <Exchange.Folder> SafeBindFolders(Exchange.ExchangeService service, IEnumerable <string> folderRemoteIds)
        {
            List <Exchange.Folder> result = new List <Exchange.Folder>();

            foreach (string uniqueId in folderRemoteIds)
            {
                if (string.IsNullOrEmpty(uniqueId))
                {
                    continue;
                }
                try {
                    Exchange.Folder folder = Exchange.Folder.Bind(service, new Exchange.FolderId(uniqueId));
                    result.Add(folder);
                } catch (Exchange.ServiceResponseException) { }
            }
            return(result);
        }
Пример #28
0
        public List <OutlookAppointment> GetCalendarEntries()
        {
            List <OutlookAppointment> appointments = new List <OutlookAppointment>();
            var _service = new Microsoft.Exchange.WebServices.Data.ExchangeService(Microsoft.Exchange.WebServices.Data.ExchangeVersion.Exchange2010_SP1);

            _service.Credentials = new Microsoft.Exchange.WebServices.Data.WebCredentials(Settings.Instance.ExchageUser, Settings.Instance.ExchagePassword);
            _service.Url         = new Uri(Settings.Instance.ExchageServerAddress);
            var items = _service.FindItems(Microsoft.Exchange.WebServices.Data.WellKnownFolderName.Calendar, new Microsoft.Exchange.WebServices.Data.ItemView(int.MaxValue));

            foreach (Microsoft.Exchange.WebServices.Data.Appointment appointment in items)
            {
                OutlookAppointment newAppointment = GetOutlookAppointment(appointment, _service);

                appointments.Add(newAppointment);
            }
            return(appointments);
        }
Пример #29
0
        public List <OutlookAppointment> GetCalendarEntriesInRange()
        {
            List <OutlookAppointment> appointments = new List <OutlookAppointment>();
            var service = new Microsoft.Exchange.WebServices.Data.ExchangeService(Microsoft.Exchange.WebServices.Data.ExchangeVersion.Exchange2010_SP1);

            service.Credentials = new Microsoft.Exchange.WebServices.Data.WebCredentials(Settings.Instance.ExchageUser, Settings.Instance.ExchagePassword);

            if (string.IsNullOrWhiteSpace(Settings.Instance.ExchageServerAddress))
            {
                service.AutodiscoverUrl(Settings.Instance.ExchageUser, ValidateRedirectionUrlCallback);
            }
            else
            {
                service.Url = new Uri(Settings.Instance.ExchageServerAddress + "/EWS/Exchange.asmx");
            }

            DateTime min = DateTime.Now.AddDays(-Settings.Instance.DaysInThePast);
            DateTime max = DateTime.Now.AddDays(+Settings.Instance.DaysInTheFuture + 1);

            var calView = new Microsoft.Exchange.WebServices.Data.CalendarView(min, max);

            calView.PropertySet = new PropertySet(
                BasePropertySet.IdOnly,
                AppointmentSchema.Subject,
                AppointmentSchema.Start,
                AppointmentSchema.IsRecurring,
                AppointmentSchema.AppointmentType,
                AppointmentSchema.End,
                AppointmentSchema.IsAllDayEvent,
                AppointmentSchema.Location,
                AppointmentSchema.Organizer,
                AppointmentSchema.ReminderMinutesBeforeStart,
                AppointmentSchema.IsReminderSet
                );

            FindItemsResults <Appointment> findResults = service.FindAppointments(WellKnownFolderName.Calendar, calView);

            foreach (Appointment appointment in findResults.Items)
            {
                OutlookAppointment newAppointment = GetOutlookAppointment(appointment, service);
                appointments.Add(newAppointment);
            }

            return(appointments);
        }
Пример #30
0
        private void button1_Click(object sender, EventArgs e)
        {
            Exchange.ExchangeService eService = new Exchange.ExchangeService(Exchange.ExchangeVersion.Exchange2007_SP1);
            eService.Credentials = new Exchange.WebCredentials("*****@*****.**", "sFx2Dobay");
            eService.Url         = new Uri("https://outlook.office365.com/ews/Exchange.asmx");
            //eService.TimeZone = TimeZoneInfo.Local;
            //eService.ImpersonatedUserId = new Exchange.ImpersonatedUserId(Exchange.ConnectingIdType.SmtpAddress, "*****@*****.**");
            Exchange.Task nTask = new Exchange.Task(eService);

            Exchange.MessageBody messageBody = new Exchange.MessageBody(Exchange.BodyType.HTML, "Необходимо строчно сделать эту работу");

            nTask.Body          = messageBody;
            nTask.Subject       = "Очень важная задача";
            nTask.Importance    = Exchange.Importance.High;
            nTask.StartDate     = DateTime.Today.AddDays(1).AddHours(8);
            nTask.IsReminderSet = true;
            nTask.DueDate       = DateTime.Today.AddDays(3).AddHours(14);
            nTask.Save(new Exchange.FolderId(Exchange.WellKnownFolderName.Tasks, new Exchange.Mailbox("*****@*****.**")));
        }
Пример #31
0
        public void GetUnReadMailCountByUserMailAddress()
        {
            int unRead = 0;

            try
            {
                Microsoft.Exchange.WebServices.Data.ExchangeService service = new Microsoft.Exchange.WebServices.Data.ExchangeService(Microsoft.Exchange.WebServices.Data.ExchangeVersion.Exchange2013_SP1);
                service.Credentials        = new NetworkCredential(exconfig.AdminAccount, exconfig.AdminPwd, exconfig.Ldap);
                service.Url                = new Uri($"http://{exconfig.ServerIpOrDomain}/ews/exchange.asmx");
                service.ImpersonatedUserId = new Microsoft.Exchange.WebServices.Data.ImpersonatedUserId(Microsoft.Exchange.WebServices.Data.ConnectingIdType.SmtpAddress, "*****@*****.**");
                unRead = Microsoft.Exchange.WebServices.Data.Folder.Bind(service, Microsoft.Exchange.WebServices.Data.WellKnownFolderName.Inbox).UnreadCount;
            }
            catch (Exception ex)
            {
                Console.Write(ex);
            }

            Console.Write(unRead);;
        }
Пример #32
0
        public List<OutlookAppointment> GetCalendarEntriesInRange()
        {
            List<OutlookAppointment> appointments = new List<OutlookAppointment>();
            var service = new Microsoft.Exchange.WebServices.Data.ExchangeService(Microsoft.Exchange.WebServices.Data.ExchangeVersion.Exchange2010_SP1);
            service.Credentials = new Microsoft.Exchange.WebServices.Data.WebCredentials(Settings.Instance.ExchageUser, Settings.Instance.ExchagePassword);

            if (string.IsNullOrWhiteSpace(Settings.Instance.ExchageServerAddress))
            {
                service.AutodiscoverUrl(Settings.Instance.ExchageUser, ValidateRedirectionUrlCallback);
            }
            else
            {
                service.Url = new Uri(Settings.Instance.ExchageServerAddress + "/EWS/Exchange.asmx");
            }

            DateTime min = DateTime.Now.AddDays(-Settings.Instance.DaysInThePast);
            DateTime max = DateTime.Now.AddDays(+Settings.Instance.DaysInTheFuture + 1);

            var calView = new Microsoft.Exchange.WebServices.Data.CalendarView(min, max);
            calView.PropertySet = new PropertySet(
                BasePropertySet.IdOnly,
                AppointmentSchema.Subject,
                AppointmentSchema.Start,
                AppointmentSchema.IsRecurring,
                AppointmentSchema.AppointmentType,
                AppointmentSchema.End,
                AppointmentSchema.IsAllDayEvent,
                AppointmentSchema.Location,
                AppointmentSchema.Organizer,
                AppointmentSchema.ReminderMinutesBeforeStart,
                AppointmentSchema.IsReminderSet
                );

            FindItemsResults<Appointment> findResults = service.FindAppointments(WellKnownFolderName.Calendar, calView);

            foreach (Appointment appointment in findResults.Items)
            {
                OutlookAppointment newAppointment = GetOutlookAppointment(appointment, service);
                appointments.Add(newAppointment);
            }

            return appointments;
        }
        /// <summary>
        /// Attempts to bind <see cref="Exchange.Folder"/> items by <paramref name="folderRemoteIds"/> collection.
        /// The method returns only folders which can not be obtained.
        /// </summary>
        /// <param name="service"><see cref="Exchange.ExchangeService"/> instance.</param>
        /// <param name="folderRemoteIds">Exchange folders remote ids collection.</param>
        /// <param name="context"><see cref="SyncContext"/> instance.</param>
        /// <returns>Folders which can not be obtained.</returns>
        protected virtual List <Exchange.Folder> SafeBindFolders(Exchange.ExchangeService service,
                                                                 IEnumerable <string> folderRemoteIds, SyncContext context)
        {
            List <Exchange.Folder> result = new List <Exchange.Folder>();

            foreach (string uniqueId in folderRemoteIds)
            {
                if (string.IsNullOrEmpty(uniqueId))
                {
                    continue;
                }
                try {
                    Exchange.Folder folder = Exchange.Folder.Bind(service, new Exchange.FolderId(uniqueId));
                    result.Add(folder);
                } catch (Exchange.ServiceResponseException exception) {
                    LogMessage(context, SyncAction.None, SyncDirection.Upload, "Error while folder bind. Folder remoteId {0}", exception, uniqueId);
                }
            }
            return(result);
        }
Пример #34
0
        public void start()
        {
            if (_service != null)
            {
                OnStateChanged(new StatusEventArgs(StatusType.error, "Already connected"));
                return;
            }
            try
            {
                serviceURL = ExchangeWebServiceURL;
                // Hook up the cert callback.
                System.Net.ServicePointManager.ServerCertificateValidationCallback =
                    delegate(
                        Object obj,
                        X509Certificate certificate,
                        X509Chain chain,
                        SslPolicyErrors errors)
                    {
                        // Validate the certificate and return true or false as appropriate.
                        // Note that it not a good practice to always return true because not
                        // all certificates should be trusted.

                        // If the certificate is a valid, signed certificate, return true.
                        if (errors == System.Net.Security.SslPolicyErrors.None)
                        {
                            OnStateChanged(new StatusEventArgs(StatusType.validating, "No error"));
                            return true;
                        }
                        // If there are errors in the certificate chain, look at each error to determine the cause.
                        if ((errors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
                        {
                            OnStateChanged(new StatusEventArgs(StatusType.validating, "validating certificate"));
                            if (chain != null && chain.ChainStatus != null)
                            {
                                foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
                                {
                                    if ((certificate.Subject == certificate.Issuer) &&
                                       (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
                                    {
                                        // Self-signed certificates with an untrusted root are valid.
                                        continue;
                                    }
                                    else
                                    {
                                        if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
                                        {
                                            // If there are any other errors in the certificate chain, the certificate is invalid,
                                            // so the method returns false.
                                            helpers.addLog("certificate not validated");
                                            OnStateChanged(new StatusEventArgs(StatusType.validating, "certificate not validated"));
                                            return false;
                                        }
                                    }
                                }
                            }

                            // When processing reaches this line, the only errors in the certificate chain are
                            // untrusted root errors for self-signed certificates. These certificates are valid
                            // for default Exchange server installations, so return true.
                            helpers.addLog("certificate validated");
                            OnStateChanged(new StatusEventArgs(StatusType.validating, "certificate validated"));
                            return true;
                        }
                        else
                        {
                            // In all other cases, return false.
                            helpers.addLog("certificate not validated");
                            OnStateChanged(new StatusEventArgs(StatusType.validating, "certificate not validated"));
                            return false;
                        }

                    };

                _service = new ExchangeService(Microsoft.Exchange.WebServices.Data.ExchangeVersion.Exchange2010_SP2);

                if (_enableTrace)
                {
                    _service.TraceListener = new TraceListener();// ITraceListenerInstance;
                    // Optional flags to indicate the requests and responses to trace.
                    _service.TraceFlags = TraceFlags.EwsRequest | TraceFlags.EwsResponse;
                    _service.TraceEnabled = true;
                }
            }
            catch (Exception ex)
            {
                helpers.addLog("Exception: " + ex.Message);
            }
        }
Пример #35
0
        private static webServiceData.ExchangeService getWebService(SchedulingInfo schedulingInfo){

            long now = DateTime.UtcNow.Ticks;
            RvLogger.DebugWrite("start to create webservice======================================");
            ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;

            webServiceData.ExchangeService service = new webServiceData.ExchangeService(webServiceData.ExchangeVersion.Exchange2010_SP2);

            String userAccount = null;
            if (settingsInfo.ContainsKey("ExchangeServer.email.account"))
                userAccount = settingsInfo["ExchangeServer.email.account"];

            if(settingsInfo.ContainsKey("ExchangeServer.user.account"))
                userAccount = settingsInfo["ExchangeServer.user.account"];
            String userPassword = null;
            if (settingsInfo.ContainsKey("ExchangeServer.email.password"))
                userPassword = settingsInfo["ExchangeServer.email.password"];
            if (settingsInfo.ContainsKey("ExchangeServer.user.password"))
                userPassword = settingsInfo["ExchangeServer.user.password"];

            String userEmail = null;
            if (settingsInfo.ContainsKey("ExchangeServer.email.account"))
                userEmail = settingsInfo["ExchangeServer.email.account"];
            if (settingsInfo.ContainsKey("ExchangeServer.user.email"))
                userEmail = settingsInfo["ExchangeServer.user.email"];

            RvLogger.DebugWrite("EXCHANGE_USER: "******"EXCHANGE_EMAIL: " + userEmail);
            RvLogger.DebugWrite("EXCHANGE_password: "******"AutodiscoverUrl Error: " + e.Message);
                RvLogger.InfoWrite(e.StackTrace);
                service.TraceEnabled = true;
                service.TraceListener = new TraceListener();
                service.TraceFlags = webServiceData.TraceFlags.All;
                try
                {
                    service.AutodiscoverUrl(userEmail, RedirectionUrlValidationCallback);
                }
                catch (Exception e1)
                {
                    RvLogger.InfoWrite("AutodiscoverUrl Error1: " + e1.Message);
                    RvLogger.InfoWrite(e1.StackTrace);
                    if (settingsInfo.ContainsKey("ExchangeServer.ewsurl"))
                    {
                        String ewsurl = settingsInfo["ExchangeServer.ewsurl"];
                        service.Url = new Uri(ewsurl);
                    }
                    if (settingsInfo.ContainsKey("ExchangeServer.trace.all"))
                    {
                        String traceAll = settingsInfo["ExchangeServer.trace.all"];
                        if (traceAll != null && !traceAll.Equals("true"))
                        {
                            service.TraceEnabled = false;
                            service.TraceListener = null;
                        }
                    }

                }
            }
            RvLogger.DebugWrite("Discovered service URL:"+service.Url);
            if (null != schedulingInfo)
                service.ImpersonatedUserId = new webServiceData.ImpersonatedUserId(webServiceData.ConnectingIdType.SmtpAddress, schedulingInfo.delegatorEmailAddr);

            RvLogger.DebugWrite("Finished to create webservice======================================time:" + (DateTime.UtcNow.Ticks - now));

            return service;
        }