public static ExchangeService CreateConnection(string emailAddress) { // Hook up the cert callback to prevent error if Microsoft.NET doesn't trust the server ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }; ExchangeService service = null; if (!string.IsNullOrEmpty(Configuration.ExchangeAddress)) { service = new ExchangeService(); service.Url = new Uri(Configuration.ExchangeAddress); } else { if (!string.IsNullOrEmpty(emailAddress)) { service = new ExchangeService(); service.AutodiscoverUrl(emailAddress); } } return service; }
public static Func<ExchangeService> GetExchangeServiceBuilder(string username, string password, string serviceUrl) { // if we don't get a service URL in our configuration, run auto-discovery the first time we need it var svcUrl = new Lazy<string>(() => { if (!string.IsNullOrEmpty(serviceUrl)) { return serviceUrl; } var log = log4net.LogManager.GetLogger(MethodInfo.GetCurrentMethod().DeclaringType); log.DebugFormat("serviceUrl wasn't configured in appSettings, running auto-discovery"); var svc = new ExchangeService(ExchangeVersion.Exchange2010_SP1); svc.Credentials = new WebCredentials(username, password); svc.AutodiscoverUrl(username, url => new Uri(url).Scheme == "https"); log.DebugFormat("Auto-discovery complete - found URL: {0}", svc.Url); return svc.Url.ToString(); }); return () => new ExchangeService(ExchangeVersion.Exchange2010_SP1) { Credentials = new WebCredentials(username, password), Url = new Uri(svcUrl.Value), }; }
public static ExchangeService GetExchangeService(string emailAddress, string username, string password, ExchangeVersion exchangeVersion, Uri serviceUri) { var service = new ExchangeService(exchangeVersion); service.Credentials = new WebCredentials(username, password); service.EnableScpLookup = false; if (serviceUri == null) { service.AutodiscoverUrl(emailAddress, (url) => { bool result = false; var redirectionUri = new Uri(url); if (redirectionUri.Scheme == "https") { result = true; } return result; }); } else { service.Url = serviceUri; } return service; }
private static void Main(string[] args) { //ExchangeService service = new ExchangeService(); ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1, TimeZoneInfo.Local) { UseDefaultCredentials = true }; service.AutodiscoverUrl(@"*****@*****.**"); Task newTask = new Task(service); newTask.Contacts.Add("*****@*****.**"); newTask.DueDate = DateTime.Now.AddDays(1); newTask.PercentComplete = 48; newTask.StartDate = DateTime.Now; newTask.Status = TaskStatus.InProgress; //newTask.TotalWork = 50; newTask.Body = "Hello"; newTask.Subject = "Test Issue Task"; newTask.ReminderDueBy = newTask.DueDate.Value; IList<Task> items = new List<Task>(); items.Add(newTask); FolderId id = new FolderId(WellKnownFolderName.Tasks); //service.CreateItems(items, id, null, null); }
public static ExchangeService ConnectToServiceWithImpersonation( IUserData userData, string impersonatedUserSMTPAddress, ITraceListener listener) { ExchangeService service = new ExchangeService(userData.Version); if (listener != null) { service.TraceListener = listener; service.TraceFlags = TraceFlags.All; service.TraceEnabled = true; } service.Credentials = new NetworkCredential(userData.EmailAddress, userData.Password); ImpersonatedUserId impersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, impersonatedUserSMTPAddress); service.ImpersonatedUserId = impersonatedUserId; if (userData.AutodiscoverUrl == null) { service.AutodiscoverUrl(userData.EmailAddress, RedirectionUrlValidationCallback); userData.AutodiscoverUrl = service.Url; } else { service.Url = userData.AutodiscoverUrl; } return service; }
/// <summary> /// Connect to Exchange using AutoDiscover for the given email address /// </summary> /// <param name="UseDefaultCredentials">if set to true, UserName and Password will be ignored and the session credentials will be used</param> /// <param name="UserName">UserName for the connection</param> /// <param name="Password">Password for the connection</param> /// <param name="Mailbox">If Impersonate is true, the Mailbox is neeed which should be impersonated</param> /// <param name="AllowRedirection">Should normaly set to true </param> /// <param name="Impersonate">If a mailbox should be impersonated, this need to be set to true</param> /// <param name="IgnoreCertificateErrors">At now not implemented. Will be Ignored.</param> /// <returns>Exchange Web Service binding</returns> public ExchangeService Service(bool UseDefaultCredentials, string UserName, SecureString Password, string Mailbox, bool AllowRedirection, bool Impersonate, bool IgnoreCertificateErrors) { log.WriteDebugLog("Connecting to exchange with following settings:"); log.WriteDebugLog(string.Format("UseDefaultCredentials: {0}", UseDefaultCredentials.ToString())); if (UserName.Length > 0) { log.WriteDebugLog(string.Format("UserName: {0}", UserName)); } if (Password != null) { log.WriteDebugLog("Passwort: set"); } log.WriteDebugLog(string.Format("Mailbox: {0}", Mailbox)); log.WriteDebugLog(string.Format("AllowRedirection: {0}", AllowRedirection.ToString())); log.WriteDebugLog(string.Format("Impersonate: {0}", Impersonate.ToString())); log.WriteDebugLog(string.Format("IgnoreCertificateErrors: {0}", IgnoreCertificateErrors.ToString())); if (IgnoreCertificateErrors) { ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; } var service = new ExchangeService(); try { if (UseDefaultCredentials) { service.UseDefaultCredentials = true; } else { service.Credentials = new WebCredentials(UserName, SecureStringHelper.SecureStringToString(Password)); } if (AllowRedirection) { service.AutodiscoverUrl(Mailbox, url => true); } else { service.AutodiscoverUrl(Mailbox); } if (Impersonate) { service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, Mailbox); } log.WriteDebugLog("Service successfully created."); return(service); } catch (Exception ex) { log.WriteErrorLog("Error on creating service."); log.WriteErrorLog(string.Format("Exception: {0}", ex.Message)); return(null); } }
static private EWSConnection ConnectToEWS(Credentials credentials) { Logger.DebugFormat("Initializing FolderMailboxManager for email adderss {0}", credentials.EmailAddress); var exchangeService = new ExchangeService(ExchangeVersion.Exchange2010_SP1) { Credentials = new WebCredentials(credentials.UserName, credentials.Password), Timeout = 60000 }; exchangeService.AutodiscoverUrl( credentials.EmailAddress, x => { Logger.DebugFormat("Following redirection for EWS autodiscover: {0}", x); return(true); } ); Logger.DebugFormat("Service URL: {0}", exchangeService.Url); return(new EWSConnection() { Service = exchangeService, Router = new RecipientsMailboxManagerRouter( new EWSMailFolder(Folder.Bind(exchangeService, WellKnownFolderName.Inbox))) }); }
private void btnGetCourses_Click(object sender, EventArgs e) { try { //Initializing Service, Message exchange = new ExchangeService(ExchangeVersion.Exchange2013); //Defining Service Credentials exchange.Credentials = new WebCredentials(tbEmail.Text, tbPassword.Text, "AutodiscoverUrl"); exchange.AutodiscoverUrl(tbEmail.Text, RedirectionCallback); System.Threading.Tasks.Task.Run(() => { MessageBox.Show("Connected!\nFetching Email..."); }); GetEmails(); } catch (Exception ex) { if (ex.Message.Contains("The Autodiscover service couldn't be located.")) { MessageBox.Show("Wrong Email or Password"); return; } MessageBox.Show(ex.Message + "\n\n" + ex); } }
public void Execute(IActivityRequest request, IActivityResponse response) { userName = settings.UserName; password = settings.Password; domain = settings.Domain; exchangeVersion = settings.ExchangeVersion; serviceURL = settings.ServiceUrl; AppointmentID = request.Inputs["Appointment Id"].AsString(); StartDate = request.Inputs["Start Date"].AsString(); EndDate = request.Inputs["End Date"].AsString(); Calendar = request.Inputs["Calendar Name"].AsString(); string alternateMailbox = string.Empty; if (request.Inputs.Contains("Alternate Mailbox")) { alternateMailbox = request.Inputs["Alternate Mailbox"].AsString(); } ExchangeService service = new ExchangeService(); switch (exchangeVersion) { case "Exchange2007_SP1": service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); break; case "Exchange2010": service = new ExchangeService(ExchangeVersion.Exchange2010); break; case "Exchange2010_SP1": service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); break; default: service = new ExchangeService(); break; } service.Credentials = new WebCredentials(userName, password, domain); String AccountUrl = userName + "@" + domain; if (serviceURL.Equals("Autodiscover")) { service.AutodiscoverUrl(AccountUrl); } else { service.Url = new Uri(serviceURL); } if (!alternateMailbox.Equals(String.Empty)) { service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, alternateMailbox); } response.WithFiltering().PublishRange(getAppointment(service)); }
public static Func <ExchangeService> GetExchangeServiceBuilder(string username, string password, string serviceUrl) { // if we don't get a service URL in our configuration, run auto-discovery the first time we need it var svcUrl = new Lazy <string>(() => { if (!string.IsNullOrEmpty(serviceUrl)) { return(serviceUrl); } __log.DebugFormat("serviceUrl wasn't configured in appSettings, running auto-discovery"); var svc = new ExchangeService(ExchangeVersion.Exchange2010_SP1); svc.Credentials = new WebCredentials(username, password); svc.PreAuthenticate = true; svc.AutodiscoverUrl(username, url => new Uri(url).Scheme == "https"); __log.DebugFormat("Auto-discovery complete - found URL: {0}", svc.Url); return(svc.Url.ToString()); }); return(() => new ExchangeService(ExchangeVersion.Exchange2010_SP1) { Credentials = new WebCredentials(username, password), Url = new Uri(svcUrl.Value), PreAuthenticate = true, }); }
public static void Start(Configuration config, IEnumerable <IAcceptEmails> emailHandlers) { ServicePointManager.ServerCertificateValidationCallback = EwsAuthentication.CertificateValidationCallBack; var creds = config.Get("email-auth").Split(':'); var userName = creds[0]; var password = creds[1]; var ewsUrl = config.GetWithDefault("email-ews-url", null); var service = new ExchangeService(ExchangeVersion.Exchange2010_SP1) { Credentials = new WebCredentials(userName, password), TraceEnabled = false, TraceFlags = TraceFlags.None }; if (ewsUrl != null) { Trace.WriteLine("Setting EWS url to " + ewsUrl); service.Url = new Uri(ewsUrl); } else { Trace.WriteLine("Starting autodiscover for EWS url..."); service.AutodiscoverUrl(userName, EwsAuthentication.RedirectionUrlValidationCallback); Trace.WriteLine(string.Format("Got {0} for EWS url", service.Url)); } SubscribeToNewMails(service, emailHandlers.ToList()); Trace.WriteLine("Waiting for EWS notifications..."); }
private bool UnreadAutopsyRequestExist() { bool result = false; ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.Credentials = new WebCredentials("ypiilab\\histology", "Let'sMakeSlides"); service.TraceEnabled = true; service.TraceFlags = TraceFlags.All; service.AutodiscoverUrl("*****@*****.**", RedirectionUrlValidationCallback); SearchFilter searchFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false); List <SearchFilter> searchFilterCollection = new List <SearchFilter>(); searchFilterCollection.Add(searchFilter); ItemView view = new ItemView(50); view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived); view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending); view.Traversal = ItemTraversal.Shallow; FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, view); if (findResults.Items.Count > 0) { result = true; } return(result); }
public static ExchangeService ConnectToService( IUserData userData, ITraceListener listener) { ExchangeService service = new ExchangeService(userData.Version); if (listener != null) { service.TraceListener = listener; service.TraceFlags = TraceFlags.All; service.TraceEnabled = true; } service.Credentials = new NetworkCredential(userData.EmailAddress, userData.Password); if (userData.AutodiscoverUrl == null) { service.AutodiscoverUrl(userData.EmailAddress, RedirectionUrlValidationCallback); userData.AutodiscoverUrl = service.Url; } else { service.Url = userData.AutodiscoverUrl; } return service; }
private void resolveAccount(ExchangeAccount account) { ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack; ExchangeService service = new ExchangeService((ExchangeVersion)account.EwsVersion) { Credentials = new WebCredentials( account.Account, RsaUtil.Decrypt(account.Password) ), }; try { if (!string.IsNullOrWhiteSpace(account.Url)) { service.Url = new Uri(account.Url); } else { service.AutodiscoverUrl(account.Account, RedirectionUrlValidationCallback); } var match = service.ResolveName(account.Account); if (match.Count == 0) { throw new Exception(); } } catch (Exception) { ModelState.AddModelError("Account", Resources.CouldNotBeResolved); } }
public ExchangeService GetExchangeService(ExchangeServerSettings exchangeServerSettings) { ExchangeVersion exchangeVersion; var isValidVersion = Enum.TryParse(exchangeServerSettings.ExchangeVersion, true, out exchangeVersion); if (isValidVersion) { var service = new ExchangeService(exchangeVersion) { UseDefaultCredentials = exchangeServerSettings.UsingCorporateNetwork, EnableScpLookup = false, Url = new Uri(exchangeServerSettings.ExchangeServerUrl) }; if (string.IsNullOrEmpty(exchangeServerSettings.ExchangeServerUrl)) { service.AutodiscoverUrl(exchangeServerSettings.EmailId); } if (!exchangeServerSettings.UsingCorporateNetwork) { service.Credentials = new WebCredentials(exchangeServerSettings.EmailId, exchangeServerSettings.Password, exchangeServerSettings.Domain); } //service.Credentials = new WebCredentials("*****@*****.**", "password"); return service; } return null; }
/// <summary> /// Get bindings for exchange web service. /// Will take more time if AutodiscoverUrl value is not defined in app.config file. /// </summary> /// <returns></returns> static ExchangeService GetBinding() { try { ExchangeService service = new ExchangeService(); service.Credentials = new WebCredentials(ConfigurationManager.AppSettings["UserID"].ToString(), ConfigurationManager.AppSettings["Password"].ToString()); try { // Check if AutodiscoverUrl is given in App.config file. if (ConfigurationManager.AppSettings["AutodiscoverUrl"].ToString() == "") { service.AutodiscoverUrl(ConfigurationManager.AppSettings["UserID"].ToString(), RedirectionUrlValidationCallback); } else { service.Url = new System.Uri(ConfigurationManager.AppSettings["AutodiscoverUrl"]); } } catch (AutodiscoverRemoteException) { throw; } return(service); } catch (Exception) { throw; } }
public static ExchangeService ConnectToServiceWithImpersonation( IUserData userData, string impersonatedUserSMTPAddress, ITraceListener listener) { ExchangeService service = new ExchangeService(userData.Version); if (listener != null) { service.TraceListener = listener; service.TraceFlags = TraceFlags.All; service.TraceEnabled = true; } service.Credentials = new NetworkCredential(userData.EmailAddress, userData.Password); ImpersonatedUserId impersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, impersonatedUserSMTPAddress); service.ImpersonatedUserId = impersonatedUserId; if (userData.AutodiscoverUrl == null) { service.AutodiscoverUrl(userData.EmailAddress, RedirectionUrlValidationCallback); userData.AutodiscoverUrl = service.Url; } else { service.Url = userData.AutodiscoverUrl; } return(service); }
public static ExchangeService ConnectToService(IUserData userData, ITraceListener listener) { ExchangeService service = new ExchangeService(userData.Version); if (listener != null) { service.TraceListener = listener; service.TraceFlags = TraceFlags.All; service.TraceEnabled = true; } service.Credentials = new NetworkCredential(userData.EmailAddress, userData.Password); if (userData.AutodiscoverUrl == null) { Console.Write(string.Format("Using Autodiscover to find EWS URL for {0}. Please wait... ", userData.EmailAddress)); service.AutodiscoverUrl(userData.EmailAddress, RedirectionUrlValidationCallback); userData.AutodiscoverUrl = service.Url; Console.WriteLine("Autodiscover Complete"); } else { service.Url = userData.AutodiscoverUrl; } return(service); }
public ExchangeService CreateService(string UserID, string UserPassword, string workinghours) { ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013); service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx"); try { service.UseDefaultCredentials = false; string workingHrs =workinghours;///default from web.config string sendUserMailAddress = UserID;// ConfigSettings.settings["SenderEmail"];// Config.SenderEmail; string sendUserMailPwd = UserPassword;// ConfigSettings.settings["SenderPassword"]; //Config.SenderPassword; if (sendUserMailAddress != null && sendUserMailPwd != null) { service.Credentials = new WebCredentials(sendUserMailAddress, sendUserMailPwd); service.AutodiscoverUrl(sendUserMailAddress, RedirectionUrlValidationCallback); } } catch { } return service; }
public static ExchangeService ConnectToService(IUserData userData, ITraceListener listener) { ExchangeService service = new ExchangeService(userData.Version); if (listener != null) { service.TraceListener = listener; service.TraceFlags = TraceFlags.All; service.TraceEnabled = true; } service.Credentials = new NetworkCredential(userData.EmailAddress, userData.Password); if (userData.AutodiscoverUrl == null) { Console.Write(string.Format("Using Autodiscover to find EWS URL for {0}. Please wait... ", userData.EmailAddress)); service.AutodiscoverUrl(userData.EmailAddress, RedirectionUrlValidationCallback); userData.AutodiscoverUrl = service.Url; Console.WriteLine("Autodiscover Complete"); } else { service.Url = userData.AutodiscoverUrl; } return service; }
public List <Item> GetMessages(long recordLimit) { ExchangeService service = new ExchangeService(); List <Item> messages = new List <Item>(); // Set specific credentials. service.Credentials = new NetworkCredential(UserName, Password); // Look up the user's EWS endpoint by using Autodiscover. service.AutodiscoverUrl(UserName, RedirectionCallback); // Create the item view limit based on the number of records requested from the Alteryx engine. ItemView itemView = new ItemView(recordLimit < 1 ? 1 : (recordLimit == long.MaxValue ? int.MaxValue : (int)recordLimit)); // Query items via EWS. var results = service.FindItems(Folder, QueryString, itemView); foreach (var item in results.Items) { // Bind an email message and pull the specified set of properties. Item message = Item.Bind(service, item.Id, Fields); var attachments = string.Empty; // Extract attachments from each message item if found. if (!String.IsNullOrEmpty(AttachmentPath)) { GetAttachmentsFromEmail(message); } messages.Add(message); } return(messages); }
public static void Create(List <string> emails, string subject, string body, DateTime date) { var user = ConfigurationManager.AppSettings["EmailConfig"]; var password = ConfigurationManager.AppSettings["PasswordConfig"]; ExchangeService service = new ExchangeService(); service.Credentials = new NetworkCredential(user, password); service.AutodiscoverUrl(user, RedirectionCallback); Appointment appointment = new Appointment(service); appointment.Subject = subject; appointment.Body = body; appointment.Start = date.AddHours(5); appointment.End = date.AddHours(6); appointment.ReminderDueBy = DateTime.Now; foreach (var email in emails) { appointment.RequiredAttendees.Add(email); } appointment.Save(SendInvitationsMode.SendToAllAndSaveCopy); Item item = Item.Bind(service, appointment.Id, new PropertySet(ItemSchema.Subject)); }
public void SaveAttachment(string email, string password, string downloadfolder, string fromaddress) { ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.Credentials = new WebCredentials(email, password); service.TraceEnabled = true; service.TraceFlags = TraceFlags.All; service.AutodiscoverUrl(email, RedirectionUrlValidationCallback); // Bind the Inbox folder to the service object. Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox); // The search filter to get unread email. SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)); ItemView view = new ItemView(1); // Fire the query for the unread items. // This method call results in a FindItem call to EWS. FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view); foreach (EmailMessage item in findResults) { item.Load(); /* download attachment if any */ if (item.HasAttachments && item.Attachments[0] is FileAttachment && item.From.Address == fromaddress) { FileAttachment fileAttachment = item.Attachments[0] as FileAttachment; /* download attachment to folder */ fileAttachment.Load(downloadfolder + fileAttachment.Name); } /* mark email as read */ item.IsRead = true; item.Update(ConflictResolutionMode.AlwaysOverwrite); } }
public static void EnviarContaPorEmail(Contato contato) { string corpoMsg = string.Format("<h2>Contato - LojaVirtual</h2>" + "<b>Nome: </b> {0} <br />" + "<b>E-mail: </b> {1} <br />" + "<b>Texto: </b> {2} <br />" + "<br /> Email enviado automaticamente do site lojaVirtual", contato.Nome, contato.Email, contato.Texto); ExchangeService exchange = new ExchangeService(); WebCredentials webCredentials = new WebCredentials("*****@*****.**", "BGsword368"); exchange.Credentials = webCredentials; exchange.AutodiscoverUrl("*****@*****.**"); EmailMessage message = new EmailMessage(exchange); message.Subject = "Contato lojaVirtual teste -Email: " + contato.Email; //Mensagem Assunto message.Body = corpoMsg; // Corpo do Email message.ToRecipients.Add(new EmailAddress("*****@*****.**")); // Para quem? message.ToRecipients.Add(new EmailAddress("*****@*****.**")); // Para quem? message.SendAndSaveCopy(); //enviar mensagem /* * SMTP -> Servidor que vai enviar a mensagem. */ /* * SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587); * smtp.UseDefaultCredentials = false; * smtp.Credentials = new NetworkCredential("*****@*****.**", "overload863"); * smtp.EnableSsl = true; * string corpoMsg = string.Format("<h2>Contato - LojaVirtual</h2>" + * "<b>Nome: </b> {0} <br />" + * "<b>E-mail: </b> {1} <br />" + * "<b>Texto: </b> {2} <br />" + * "<br /> Email enviado automaticamente do site lojaVirtual", * contato.Nome, * contato.Email, * contato.Texto); */ /* * MailMenssage -> Construir a Mensagem a ser enviada. */ /* * MailMessage mensagem = new MailMessage(); * * mensagem.From = new MailAddress("*****@*****.**"); //Mensagem De * mensagem.To.Add("*****@*****.**");// Mensagem Para quem? * mensagem.To.Add("*****@*****.**");// Mensagem Para quem? * mensagem.Subject = "Contato lojaVirtual teste - Email: " + contato.Email; //Mensagem Assunto * mensagem.Body = corpoMsg; // Corpo do Email * mensagem.IsBodyHtml = true; //Para habilitar HTML na mensagem * * //enviar mensagem via smtp * smtp.Send(mensagem); * */ }
private void LoginToExchangeService() { if (_exchangeService.Url == null) { _exchangeService.AutodiscoverUrl(_settingsService.ExchangeLogin, RedirectionUrlValidationCallback); } }
static void Main(string[] args) { Console.Title = "EWS Test Console"; Console.ForegroundColor = ConsoleColor.Yellow; Console.WindowHeight = Console.LargestWindowHeight * 9 / 10; Console.WindowWidth = Console.LargestWindowWidth / 2; Console.SetWindowPosition(0, 0); Console.SetBufferSize(200, 3000); // Create an instance of the custom URL redirection validator. UrlValidator validator = new UrlValidator(); // Get the user's email address and password from the console. IUserData userData = UserDataFromConsole.GetUserData(); // Create an ExchangeService object with the user's credentials. ExchangeService myService = new ExchangeService(); myService.Credentials = new NetworkCredential(userData.EmailAddress, userData.Password); Console.WriteLine("Getting EWS URL using custom validator..."); // Call the Autodisocer service with the custom URL validator. myService.AutodiscoverUrl(userData.EmailAddress, validator.ValidateUrl); Console.WriteLine(string.Format(" EWS URL is {0}", myService.Url)); Console.WriteLine("Complete"); Console.WriteLine("\r\n"); Console.WriteLine("Press or select Enter..."); Console.ReadLine(); }
/// <summary> /// Send a message using the ExchangeService api. If testmode is set then use testing values. /// </summary> /// <param name="number"></param> /// <param name="message"></param> /// <param name="region"></param> /// <param name="when"></param> /// <returns></returns> public async System.Threading.Tasks.Task SendMessage(string number, string message, string region, DateTime when) { // if not IsLive bail if (!Convert.ToBoolean(_settings.Settings["IsLive"])) { return; } number = CleanPhone(number); number = CheckTheTestMode(number); ExchangeService service = new ExchangeService(); service.Credentials = new System.Net.NetworkCredential(_cfg.Value.SystemConfig.SMSService.Exchange.Email, _cfg.Value.SystemConfig.SMSService.Exchange.Pwd); service.AutodiscoverUrl(_cfg.Value.SystemConfig.SMSService.Exchange.Email, RedirectionCallback); EmailMessage messagebody = new EmailMessage(service); //messagebody.Subject = "my subject"; messagebody.Body = message; messagebody.ToRecipients.Add($"{number}@txt.bell.ca"); //TODO go through the list of call carriers otherwise only works for users of this carrier. await messagebody.Save(); await messagebody.Send(); }
static void Main(string[] args) { ExchangeService service = new ExchangeService(); FolderId calendarId = WellKnownFolderName.Calendar; service.Credentials = new WebCredentials("svc_efsadmin", "hB7FflVLtD", "MJSC"); service.AutodiscoverUrl("*****@*****.**"); service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "*****@*****.**"); foreach (string username in ReadUsers()) { try { UpdateMasterFromLocal(service, username); if (CheckForUpdatesToLocal(service, username)) { Log.Info(String.Format("Local template category list for {0} was missing entries. Updating local template.", username)); UpdateLocalFromMaster(service, username); } } catch (Exception ex) { Log.Error("Failed to update master category list for user '" + username + ".", ex); } } }
public AppointmentGroup GetNextAppointments() { try { var newAppointments = new AppointmentGroup(); var service = new ExchangeService(); service.UseDefaultCredentials = true; service.AutodiscoverUrl(UserPrincipal.Current.EmailAddress); DateTime from = DateTime.Now.AddMinutes(-5); DateTime to = DateTime.Today.AddDays(1); IEnumerable<Appointment> appointments = service.FindAppointments(WellKnownFolderName.Calendar, new CalendarView(from, to)) .Select(MakeAppointment); newAppointments.Next = appointments.Where(o => o != null && o.Start >= DateTime.Now) .OrderBy(o => o.Start).ToList(); nextAppointments = newAppointments; return newAppointments; } catch (Exception e) { Trace.WriteLine(e.ToString()); return nextAppointments; } }
private static ExchangeService GetServiceRedirected(string email, string passw, string URL) { //Console.WriteLine("Got params " + email + " pasw " + passw + " url '" + URL + "'"); ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.Credentials = new WebCredentials(email, passw); if (URL.Length > 0) { //Console.WriteLine("Will use given url for exchange service instead auto discovery"); service.Url = new Uri(URL); } else { try { service.AutodiscoverUrl(email, RedirectionUrlValidationCallback); } catch { } finally { service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx"); } } return(service); }
private ExchangeService GetExchangeService(MailSettings settings) { var exchangeService = new ExchangeService(); if (string.IsNullOrEmpty(settings.ExchangeUserPassword)) { if (_getPasswordDelegate == null) { throw new InvalidOperationException("No password is specified and no way to get password from user"); } var password = _getPasswordDelegate(settings.ExchangeUserName); exchangeService.Credentials = new WebCredentials(new NetworkCredential(settings.ExchangeUserName, password)); } else { exchangeService.Credentials = new WebCredentials(new NetworkCredential(settings.ExchangeUserName, settings.ExchangeUserPassword)); } if (settings.AutoDiscoverUrl) { exchangeService.AutodiscoverUrl(settings.ExchangeUserName, RedirectionUrlValidationCallback); } else { exchangeService.Url = new Uri(settings.ExchangeServerUrl); } return(exchangeService); }
public static void sendEmail(List <string> ToRecipients, List <string> CcRecipients, string Subject, string Body) { ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); service.Credentials = new WebCredentials("ace_li", "t3103e7.1", "vanchip"); service.TraceEnabled = true; service.TraceFlags = TraceFlags.All; //To over-ride this behavior, we need to use the following line in the code, which validate the x509 certificate: //https://msdn.microsoft.com/en-us/library/bb408523.aspx?f=255&MSPPError=-2147217396 ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; // Set the URL. //service.Url = new Uri(@"https://mail.vanchiptech.com/ews/exchange.asmx"); service.AutodiscoverUrl("*****@*****.**", RedirectionUrlValidationCallback); EmailMessage email = new EmailMessage(service); foreach (string strTo in ToRecipients) { email.ToRecipients.Add(strTo); } foreach (string strCc in CcRecipients) { email.CcRecipients.Add(strCc); } email.Subject = Subject; email.Body = new MessageBody(Body); email.Send(); }
public bool Initialize(ref string kom) { try { OnNewFilesNumberEvent(""); OnTotalNumberOfFilesEvent(""); OnConvertedFilesNumberEvent(""); if (!Directory.Exists(mailDir)) { Directory.CreateDirectory(mailDir); } service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); service.Credentials = cred; service.TraceEnabled = true; service.TraceFlags = TraceFlags.All; service.Url = new Uri(server); service.AutodiscoverUrl(mail, new Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverRedirectionUrlValidationCallback(RedirectionCallback)); return(true); } catch (Exception ex) { kom = _rm.GetString("lblTotalGenericErrorRes") + ex.Message; return(false); } }
protected virtual void SendExchangeWebService(EmailMessageEntity email, ExchangeWebServiceEmbedded exchange) { ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.UseDefaultCredentials = exchange.UseDefaultCredentials; service.Credentials = exchange.Username.HasText() ? new WebCredentials(exchange.Username, exchange.Password) : null; //service.TraceEnabled = true; //service.TraceFlags = TraceFlags.All; if (exchange.Url.HasText()) { service.Url = new Uri(exchange.Url); } else { service.AutodiscoverUrl(email.From.EmailAddress, RedirectionUrlValidationCallback); } EmailMessage message = new EmailMessage(service); foreach (var a in email.Attachments.Where(a => a.Type == EmailAttachmentType.Attachment)) { var fa = message.Attachments.AddFileAttachment(a.File.FileName, a.File.GetByteArray()); fa.ContentId = a.ContentId; } message.ToRecipients.AddRange(email.Recipients.Where(r => r.Kind == EmailRecipientKind.To).Select(r => r.ToEmailAddress()).ToList()); message.CcRecipients.AddRange(email.Recipients.Where(r => r.Kind == EmailRecipientKind.Cc).Select(r => r.ToEmailAddress()).ToList()); message.BccRecipients.AddRange(email.Recipients.Where(r => r.Kind == EmailRecipientKind.Bcc).Select(r => r.ToEmailAddress()).ToList()); message.Subject = email.Subject; message.Body = new MessageBody(email.IsBodyHtml ? BodyType.HTML : BodyType.Text, email.Body.Text); message.Send(); }
public static ExchangeService CreateConnection(string emailAddress) { // Hook up the cert callback to prevent error if Microsoft.NET doesn't trust the server ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return(true); }; ExchangeService service = null; var exchangeAddress = Settings.GetValue <string>(MailHelper.MAILPROCESSOR_SETTINGS, MailHelper.SETTINGS_EXCHANGEADDRESS); if (!string.IsNullOrEmpty(exchangeAddress)) { service = new ExchangeService { Url = new Uri(exchangeAddress) }; } else { if (!string.IsNullOrEmpty(emailAddress)) { service = new ExchangeService(); service.AutodiscoverUrl(emailAddress); } } return(service); }
public static ExchangeService ConnectToService(IUserData userData, ITraceListener listener) { ExchangeService service = new ExchangeService(userData.Version); if (listener != null) { service.TraceListener = listener; service.TraceFlags = TraceFlags.All; service.TraceEnabled = true; } service.Credentials = new NetworkCredential(userData.EmailAddress, userData.Password); if (userData.AutodiscoverUrl == null) { service.AutodiscoverUrl(userData.EmailAddress, RedirectionUrlValidationCallback); userData.AutodiscoverUrl = service.Url; } else { service.Url = userData.AutodiscoverUrl; } return(service); }
public void SendMailMessage(SendMailOptions options) { var service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); service.Credentials = new WebCredentials(options.FromUsername, options.FromPassword); service.TraceEnabled = true; service.TraceFlags = TraceFlags.All; service.AutodiscoverUrl(options.From, RedirectionUrlValidationCallback); EmailMessage email = new EmailMessage(service); var mails = options.To.Split(','); foreach (var mail in mails) { log("adding: '" + mail.Trim() + "'"); email.ToRecipients.Add(mail.Trim()); } email.Subject = options.Subject; email.Body = new MessageBody(options.Body); email.Body.BodyType = BodyType.HTML; email.Send(); }
public ExchangeService GetExchangeService(ExchangeServerSettings exchangeServerSettings) { ExchangeVersion exchangeVersion; var isValidVersion = Enum.TryParse(exchangeServerSettings?.ExchangeVersion, true, out exchangeVersion); if (isValidVersion) { var service = new ExchangeService(exchangeVersion) { UseDefaultCredentials = exchangeServerSettings.UsingCorporateNetwork, EnableScpLookup = false, Url = new Uri(exchangeServerSettings.ExchangeServerUrl) }; if (string.IsNullOrEmpty(exchangeServerSettings.ExchangeServerUrl)) { service.AutodiscoverUrl(exchangeServerSettings.EmailId); } if (!exchangeServerSettings.UsingCorporateNetwork) { service.Credentials = new WebCredentials(exchangeServerSettings.EmailId, exchangeServerSettings.Password, exchangeServerSettings.Domain); } //service.Credentials = new WebCredentials("*****@*****.**", "password"); return(service); } return(null); }
static ExchangeService GetBinding(string emailAddress, string password) { // Create the binding. ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); // Define credentials. service.Credentials = new WebCredentials(emailAddress, password); // Use the AutodiscoverUrl method to locate the service endpoint. try { service.AutodiscoverUrl(emailAddress, RedirectionUrlValidationCallback); } catch (AutodiscoverRemoteException ex) { MessageBox.Show("Autodiscover error: " + ex.Message); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } return(service); }
private ExchangeService CreateService() { if (exchangeService != null) { return(exchangeService); } // Creating a new ExchangeService instance exchangeService = new ExchangeService(exchangeVersion); exchangeService.UseDefaultCredentials = useDefaultCredentials; exchangeService.Url = EwsUri; if (useAutodiscover) { try { toolStripStatusLabel.Text = "Performing autodiscover lookup..."; exchangeService.AutodiscoverUrl(emailAddress, delegate { return(true); }); } catch (Exception ex) { MessageBox.Show("Autodiscover wasn't able to locate your settings, please check your DNS settings or fill in the Ews Url in the settings menu./nException:/n" + ex.ToString()); toolStripStatusLabel.Text = "Autodiscover error encountered."; return(null); } } exchangeService.Credentials = new WebCredentials(username, password); exchangeService.UseDefaultCredentials = useDefaultCredentials; if (useImpersonation) { exchangeService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, emailAddress); } return(exchangeService); }
public ActionResult SignUp(SignUpView view) { String smtpAddess = "*****@*****.**"; String password = "******"; var exchangeService = new ExchangeService(ExchangeVersion.Exchange2007_SP1); exchangeService.Credentials = new WebCredentials(smtpAddess, password); exchangeService.AutodiscoverUrl(smtpAddess, RedirectionUrlValidationCallback); Contact contact = new Contact(exchangeService); contact.GivenName = view.GivenName; contact.Surname = view.Surname; contact.FileAsMapping = FileAsMapping.SurnameCommaGivenName; contact.EmailAddresses[EmailAddressKey.EmailAddress1] = new EmailAddress(view.Email); try { contact.Save(); } catch(Exception e) { ViewBag.Message = e.Message; return View(view); } return View("Thanks"); }
/// <summary> /// Initialize a new EwsClient using the specified username and password to connect to the specified version of EWS. An attempt is made to autodiscovered the EWS endpoint. /// </summary> /// <param name="username">A user with login rights on the specified <paramref name="domain"/>.</param> /// <param name="password">The password for the specified <paramref name="username"/>.</param> /// <param name="domain">The Exchange domain.</param> /// <param name="exchangeVersion">The version of Exchange.</param> /// <remarks> /// In order for autodiscovery of an EWS endpoint to work, there may be additional Exchange configuration required. /// See http://msdn.microsoft.com/en-us/library/office/jj900169(v=exchg.150).aspx. /// </remarks> public EwsClient(string username, string password, string domain, ExchangeVersion exchangeVersion) { exchangeService = new ExchangeService(exchangeVersion) { Credentials = new WebCredentials(username, password, domain), }; exchangeService.AutodiscoverUrl(String.Format("{0}@{1}", username, domain)); }
public ActionResult Login(ExLogOnViewModel model, bool hosted = false) { User userObj = (User)Session["user"]; var acc = accRepository.Accounts.FirstOrDefault(x => x.ID == userObj.AccountID); //credRepository.SetConnectionString(acc.ConnectionString); ExchangeService srv = null; if (model.SelectedCredentialID != 0) { var creds = credRepository.Credentials.FirstOrDefault(x => x.ID == model.SelectedCredentialID); if (creds.IsHostedExchange) { srv = new ExchangeService(ExchangeVersion.Exchange2007_SP1); srv.Credentials = new WebCredentials(creds.EmailAddress, creds.Password); srv.AutodiscoverUrl(creds.EmailAddress, RedirectionUrlValidationCallback); } else { if (creds.ServerVersion == "2007SP1") srv = new ExchangeService(ExchangeVersion.Exchange2007_SP1); else if (creds.ServerVersion == "2010") srv = new ExchangeService(ExchangeVersion.Exchange2010); else if (creds.ServerVersion == "2010SP1") srv = new ExchangeService(ExchangeVersion.Exchange2010_SP1); else srv = new ExchangeService(ExchangeVersion.Exchange2010_SP2); srv.Credentials = new WebCredentials(creds.UserName, creds.Password); srv.AutodiscoverUrl(creds.EmailAddress, RedirectionUrlValidationCallback); } Session["srv"] = srv; Session["srvEmail"] = creds.EmailAddress; } else { if (hosted) { srv = new ExchangeService(ExchangeVersion.Exchange2007_SP1); srv.Credentials = new WebCredentials(model.Credentials.EmailAddress, model.Credentials.Password); srv.AutodiscoverUrl(model.Credentials.EmailAddress, RedirectionUrlValidationCallback); model.Credentials.URL = srv.Url.AbsoluteUri; } else { if (model.Credentials.ServerVersion == "2007SP1") srv = new ExchangeService(ExchangeVersion.Exchange2007_SP1); else if (model.Credentials.ServerVersion == "2010") srv = new ExchangeService(ExchangeVersion.Exchange2010); else if (model.Credentials.ServerVersion == "2010SP1") srv = new ExchangeService(ExchangeVersion.Exchange2010_SP1); else srv = new ExchangeService(ExchangeVersion.Exchange2010_SP2); srv.Credentials = new WebCredentials(model.Credentials.UserName, model.Credentials.Password); srv.AutodiscoverUrl(model.Credentials.EmailAddress, RedirectionUrlValidationCallback); model.Credentials.URL = srv.Url.AbsoluteUri; } Session["srv"] = srv; Session["srvEmail"] = model.Credentials.EmailAddress; model.Credentials.IsHostedExchange = hosted; credRepository.SaveCredential(model.Credentials); } return Redirect(model.ReturnUrl); }
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"; } }
static int Main(string[] args) { if (args.Length != 2) { Console.Error.WriteLine("Usage: mail [email protected] subject"); return 1; } try { string account = System.Environment.GetEnvironmentVariable("EMAIL"); if (account == null) { Console.Error.WriteLine("Set an environment variable called EMAIL with YOUR e-mail address."); return 2; } string message = ReadStdin(); if (message.Length == 0) { Console.Error.WriteLine("No mail sent since stdin was empty."); return 3; } Console.WriteLine("Sending e-mail using account '{0}'", account); ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.Credentials = new WebCredentials(account, ""); service.UseDefaultCredentials = true; // For verbose logging /*service.TraceEnabled = true; service.TraceFlags = TraceFlags.All;*/ service.AutodiscoverUrl(account, RedirectionUrlValidationCallback); EmailMessage email = new EmailMessage(service); email.ToRecipients.Add(args[0]); email.Subject = args[1]; message = message.Replace("\n", "<br/>\n"); email.Body = new MessageBody(message); email.Send(); Console.WriteLine("Email successfully sent to '{0}'", args[0]); } catch (Exception e) { Console.WriteLine(e); return 4; } return 0; }
public static void Main(string[] args) { ServicePointManager.ServerCertificateValidationCallback = EwsAuthentication.CertificateValidationCallBack; System.Console.WriteLine("Enter your email address"); // ReSharper disable once PossibleNullReferenceException var userName = System.Console.ReadLine().Trim(); var startDate = DateTime.Now - TimeSpan.FromDays(365*6); while (startDate.DayOfWeek != DayOfWeek.Monday) { startDate -= TimeSpan.FromDays(1); } List<Meeting> meetings = null; if (File.Exists(userName)) { meetings = JsonConvert.DeserializeObject<List<Meeting>>(File.ReadAllText(userName)); } else { System.Console.WriteLine("Looks like I need to connect to Exchange. Enter your password. I won't steal it. Honest"); var password = Console.ReadPassword(); var service = new ExchangeService(ExchangeVersion.Exchange2007_SP1) { Credentials = new WebCredentials(userName, password), TraceEnabled = false, TraceFlags = TraceFlags.None }; service.AutodiscoverUrl(userName, EwsAuthentication.RedirectionUrlValidationCallback); meetings = new ExchangeRetriever(service).MeetingStatistics(startDate, DateTime.Now); File.WriteAllText(userName, JsonConvert.SerializeObject(meetings)); } using (var streamWriter = File.CreateText("accepted_meetings.csv")) { Reports.AcceptedMeetings(meetings, streamWriter); } using (var output = File.CreateText("accepted_meetings_per_week.csv")) { Reports.TotalMeetingDuration(meetings, startDate, output); } using (var output = File.CreateText("contiguous_time_per_day.csv")) { Reports.ContiguousTimePerDay(output, meetings); } }
static void Main(string[] args) { ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack; var service = new ExchangeService(ExchangeVersion.Exchange2010_SP2) { Credentials = new WebCredentials("solar_hydro_one", "Summer270"), //TraceEnabled = true, //TraceFlags = TraceFlags.All }; service.AutodiscoverUrl("*****@*****.**", RedirectionUrlValidationCallback); var rootfolder = Folder.Bind(service, WellKnownFolderName.MsgFolderRoot); rootfolder.Load(); var fid = rootfolder.FindFolders(new FolderView(3)) .Where(folder => folder.DisplayName == "Backup") .Select(folder => folder.Id).SingleOrDefault(); var dbContext = new HydroOneMeterDataContext(); var emailItems = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10)); foreach (var eItem in emailItems) { if (eItem.Subject.Contains("Hydro One Meter Data") && eItem.HasAttachments && eItem is EmailMessage) { foreach (var fileAttachment in (EmailMessage.Bind(service, eItem.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments))).Attachments.OfType<FileAttachment>().Select(attachment => attachment as FileAttachment)) { fileAttachment.Load(); Console.WriteLine("Attachment name: " + fileAttachment.Name); var hydroOneData = ProcessData(fileAttachment.Content); if (hydroOneData.Any()) { Console.WriteLine("Inserting " + hydroOneData.Count + " rows"); dbContext.HydroOneMeters.InsertAllOnSubmit(hydroOneData); } } } eItem.Move(fid); } dbContext.SubmitChanges(); Console.WriteLine("Done ... press any key to exit"); //Console.ReadKey(); }
static void Main(string[] args) { ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.AutodiscoverUrl(UserPrincipal.Current.EmailAddress); Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox); FolderView folderView = new FolderView(inbox.ChildFolderCount); folderView.PropertySet = new PropertySet(BasePropertySet.IdOnly, FolderSchema.DisplayName, FolderSchema.ChildFolderCount); foreach(Folder folder in inbox.FindFolders(folderView)) { MarkAllAsRead(folder); } }
// TODO temporary and smelly private static ExchangeService ExchangeServiceInsideTm() { var emailAddress = WebConfigurationManager.AppSettings["emailAddress"]; var ewsUrl = WebConfigurationManager.AppSettings["internalEwsUrl"]; var service = new ExchangeService(ExchangeVersion.Exchange2010) { UseDefaultCredentials = true, Url = new Uri(ewsUrl), }; service.AutodiscoverUrl(emailAddress); return service; }
public static ExchangeService GetService(string emailAddress) { //var uri = GetExchangeUri(); var userName = Environment.GetEnvironmentVariable("CONFROOMSERVER_USER"); var password = Environment.GetEnvironmentVariable("CONFROOMSERVER_PASSWORD"); var domain = DomainName; var service = new ExchangeService(); //service.Url = new Uri(uri); service.AutodiscoverUrl(emailAddress); service.Credentials = new WebCredentials(userName, password, domain); System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); return service; }
public ExchangeService GetAuthenticatedEWSInstance() { var exchangeVersion = GetBestSuitedExchangeVersion(); var service = new ExchangeService(exchangeVersion) { //Url = new Uri(@"https://cas.etn.com/ews/exchange.asmx"), //UseDefaultCredentials = true }; //https://cas.etn.com/ews/exchange.asmx service.AutodiscoverUrl("*****@*****.**", ValidateRedirectionUrlCallback); return service; }
public ExchangeService GetMicrosoftExchangeService(ExchangeUserCredential credential) { var exchangeService = new ExchangeService(ExchangeVersion.Exchange2007_SP1); if (!string.IsNullOrEmpty(credential.EmailAddress)) { exchangeService.AutodiscoverUrl(credential.EmailAddress); } else { exchangeService.Url = new Uri(credential.ExchangeServerUrl); } exchangeService.Credentials = new WebCredentials(credential.UserName, credential.Password, credential.Domain); return exchangeService; }
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; } }
static ExchangeService GetBinding() { // Create the binding. ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); // Define credentials. service.Credentials = new WebCredentials(System.Configuration.ConfigurationManager.AppSettings["Affine.Email.User"], System.Configuration.ConfigurationManager.AppSettings["Affine.Email.Password"]); // Use the AutodiscoverUrl method to locate the service endpoint. try { service.AutodiscoverUrl(System.Configuration.ConfigurationManager.AppSettings["Affine.Email.User"], RedirectionUrlValidationCallback); } catch (AutodiscoverRemoteException ex) { Console.WriteLine("Exception thrown: " + ex.Error.Message); } return service; }
public IEnumerable<Kontakt> GetContacts(string userName, string password) { // Exchange Online is running 2010 sp1 var service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); // passing the credentials to the service instance service.Credentials = new WebCredentials(userName, password); // AutoDiscover is done by redirection to general AutoDiscover Service, so we have to allow this service.AutodiscoverUrl(userName, delegate { return true; }); // Exchange is using an search based API, so let's look for contacts in the user's contact folder... var items = service.FindItems(WellKnownFolderName.Contacts, new ItemView(100)); return items.Cast<Contact>().Select(contact => new Kontakt { Vorname = contact.GivenName, Nachname = contact.Surname, Email = contact.EmailAddresses[EmailAddressKey.EmailAddress1].Address }); }
private bool Connect() { try { if (service == null || service.Url == null) { Trace.TraceInformation("Conectando..."); service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); //creamos una nueva instancia de ExchangeService service.Credentials = new NetworkCredential(username, password); //le entregamos las credenciales. service.AutodiscoverUrl(username, RedirectionUrlValidationCallback); //mediante un callback obtenemos el endpoint especifico de la cuenta de correo. } Trace.TraceInformation("Conectado."); return true; } catch (Exception) { return false; } }
public void SendMail() { try { ExchangeService service = new ExchangeService(); service.Credentials = new NetworkCredential("user", "pass", "banglalink"); service.Url = new System.Uri(@"https://mail.banglalinkgsm.com/EWS/Exchange.asmx"); service.AutodiscoverUrl("*****@*****.**"); EmailMessage message = new EmailMessage(service); message.Subject = "Test Mail"; message.Body = "Auto Generated Test Mail"; message.ToRecipients.Add("*****@*****.**"); // message.Attachments.AddFileAttachment(""); message.Send(); //ExchangeService service = new ExchangeService(); //service.Credentials = new WebCredentials("onm_iss", "password", "banglalink"); ; //new NetworkCredential("OnMSharingDB", "password","banglalinkgsm"); //service.AutodiscoverUrl("*****@*****.**"); //service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "*****@*****.**"); ////service.na //EmailMessage message = new EmailMessage(service); //message.From = "*****@*****.**"; //message.Subject = "Test Mail"; //message.Body = "Auto Generated Test Mail"; //message.ToRecipients.Add("*****@*****.**"); ////message.ToRecipients.Add("*****@*****.**"); //message.Save(); //message.SendAndSaveCopy(); ////message.Send(); } catch(Exception ex) { throw new Exception(ex.Message); } }
static void Main(string[] args) { var service = new ExchangeService(ExchangeVersion.Exchange2010); // Setting credentials is unnecessary when you connect from a computer that is logged on to the domain. service.Credentials = new WebCredentials(Settings.Default.username, Settings.Default.password, Settings.Default.domain); // Or use NetworkCredential directly (WebCredentials is a wrapper around NetworkCredential). //To set the URL manually, use the following: //service.Url = new Uri("https://proliant32.hci.tetra.ppf.cz/EWS/Exchange.asmx"); //To set the URL by using Autodiscover, use the following: service.AutodiscoverUrl("*****@*****.**"); FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10)); foreach (Item item in findResults.Items) { Console.WriteLine(item.Subject); } }
private Boolean AutodiscoverUrl(ExchangeService service, string account) { Boolean isSuccess = false; try { Console.WriteLine("Connecting the Exchange Online, might take a while......"); service.AutodiscoverUrl(account, m_UrlBack.RedirectionUrlValidationCallback); Console.WriteLine(); Console.WriteLine("Successfully connected to Exchange server: " + service.Url + " with Account: " + account); isSuccess = true; } catch (Exception e) { Console.WriteLine("Error to connect the Exchange Online."); Console.WriteLine(e.Message); } return isSuccess; }
public override void OnMessage(string value) { try { // クライアントからメッセージが来た場合 JsonObject jsonValue = (JsonObject)JsonValue.Parse(value); this.EmailAddress = (string)((JsonPrimitive)jsonValue["address"]).Value; this.Password = (string)((JsonPrimitive)jsonValue["password"]).Value; // Exchange Online に接続 (今回はデモなので、Address は決めうち !) ExchangeVersion ver = new ExchangeVersion(); ver = ExchangeVersion.Exchange2010_SP1; sv = new ExchangeService(ver, TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time")); //sv.TraceEnabled = true; // デバッグ用 sv.Credentials = new System.Net.NetworkCredential( this.EmailAddress, this.Password); sv.EnableScpLookup = false; sv.AutodiscoverUrl(this.EmailAddress, AutodiscoverCallback); // Streaming Notification の開始 (今回はデモなので、15 分で終わり !) StreamingSubscription sub = sv.SubscribeToStreamingNotifications( new FolderId[] { new FolderId(WellKnownFolderName.Calendar) }, EventType.Created, EventType.Modified, EventType.Deleted); subcon = new StreamingSubscriptionConnection(sv, 15); // only 15 minutes ! subcon.AddSubscription(sub); subcon.OnNotificationEvent += new StreamingSubscriptionConnection.NotificationEventDelegate(subcon_OnNotificationEvent); subcon.Open(); // 準備完了の送信 ! JsonObject jsonObj = new JsonObject( new KeyValuePair<string, JsonValue>("MessageType", "Ready"), new KeyValuePair<string, JsonValue>("ServerUrl", sv.Url.ToString())); this.SendMessage(jsonObj.ToString()); } catch (Exception ex) { this.SendInternalError(ex); } base.OnMessage(value); }