/// <summary> /// Adds or updates the mail header for the specified account and mailbox. /// </summary> /// <param name="accountSettingsData">The account settings data.</param> /// <param name="mailbox">The mailbox.</param> /// <param name="mailHeader">The mail header.</param> public void AddOrUpdate(AccountSettingsData accountSettingsData, Mailbox mailbox, MailHeader mailHeader) { try { // Ensure the mail header dictionary entry exists EnsureMailHeader(accountSettingsData, mailbox); // If the header exists - update it if (this[accountSettingsData.EmailAddress][mailbox.FullName].Contains(mailHeader)) { this[accountSettingsData.EmailAddress][mailbox.FullName][this[accountSettingsData.EmailAddress][mailbox.FullName].IndexOf(mailHeader)] = mailHeader; } // Else if the header does not exist = add it else { this[accountSettingsData.EmailAddress][mailbox.FullName].Add(mailHeader); } } catch (Exception ex) { LogFile.Instance.LogError(accountSettingsData.EmailAddress, mailbox.Name, ex.ToString()); } }
/// <summary> /// Occurs when the "Connect" button is clicked. /// </summary> /// <param name="sender">The object that raised the event (bConnect).</param> /// <param name="e">The event arguments (RoutedEventArgs).</param> private async void bSave_Click(object sender, RoutedEventArgs e) { // If the mail clients is found MailClient mailClient = null; if (MainPage.Current.MailClientsDictionary.TryGetValue(SelectedAccountSettingsData.EmailAddress, out mailClient)) { // Declare the variables bool requiresReconnect = false; string accountName; string displayName; EmailService emailService; EmailServiceProvider emailServiceProvider; string emailAddress; string username; string password; string incomingEmailServer; ushort incomingEmailServerPort; bool incomingEmailServerRequiresSsl; string outgoingEmailServer; ushort outgoingEmailServerPort; bool outgoingEmailServerRequiresSsl; bool outgoingMailServerRequiresAuthentication; bool useTheSameUsernameAndPasswordToSendAndReceiveEmail; string sendUsername; string sendPassword; bool useAnEmailSignature; string emailSignature; DownloadNewEmailOptions downloadNewEmail; DownloadEmailsFromOptions downloadEmailsFrom; bool keepEmailCopiesOnServer; bool contentToSyncEmail; // If the connection info is valid if (IsConnectionInfoValid(out requiresReconnect, out accountName, out displayName, out emailService, out emailServiceProvider, out emailAddress, out username, out password, out incomingEmailServer, out incomingEmailServerPort, out incomingEmailServerRequiresSsl, out outgoingEmailServer, out outgoingEmailServerPort, out outgoingEmailServerRequiresSsl, out outgoingMailServerRequiresAuthentication, out useTheSameUsernameAndPasswordToSendAndReceiveEmail, out sendUsername, out sendPassword, out useAnEmailSignature, out emailSignature, out downloadNewEmail, out downloadEmailsFrom, out keepEmailCopiesOnServer, out contentToSyncEmail)) { // Get the account settings dat AccountSettingsData accountSettingsData = new AccountSettingsData(accountName, emailService, emailServiceProvider, displayName, emailAddress, username, password, incomingEmailServer, incomingEmailServerPort, incomingEmailServerRequiresSsl, outgoingEmailServer, outgoingEmailServerPort, outgoingEmailServerRequiresSsl, outgoingMailServerRequiresAuthentication, useTheSameUsernameAndPasswordToSendAndReceiveEmail, sendUsername, sendPassword, useAnEmailSignature, emailSignature, downloadNewEmail, downloadEmailsFrom, keepEmailCopiesOnServer, contentToSyncEmail); // If new settings require reconnect if (requiresReconnect) { // Logout if (mailClient.State.HasFlag(MailClientState.Authenticated)) { await mailClient.Logout(); } // Get the mail client mailClient = await MailClient.GetMailClient(accountSettingsData); // If login if (mailClient.Login().IsSuccessfull) { MainPage.Current.ConnectMailbox(accountSettingsData, mailClient); } } // Save the settings mailClient.AccountSettingsData = accountSettingsData; MainPage.Current.MailClientsDictionary[accountSettingsData.EmailAddress] = mailClient; StorageSettings.AccountSettingsDataDictionary[accountSettingsData.EmailAddress] = accountSettingsData; try { if (MainPage.Current.SelectedAccount.Key.Equals(accountSettingsData.EmailAddress, StringComparison.OrdinalIgnoreCase)) { MainPage.Current.AccountName = accountSettingsData.AccountName; } } catch { } MainPage.Current.BindMailboxes(accountSettingsData); await StorageSettings.SaveAccountSettingsDataDictionary(); } } }
/// <summary> /// Connect to a mailbox. /// </summary> /// <param name="accountSettingsData">The account settings data.</param> /// <param name="isLastAccountSettingsData">true, if is last account settings data; otherwise, false.</param> /// <param name="configurationNumber">The configuration number.</param> /// <param name="configurationCount">The configuration count.</param> /// <returns>true, if connected successfully; otherwise, false.</returns> private async Task <bool> Connect(AccountSettingsData accountSettingsData, bool isLastAccountSettingsData, int configurationNumber, int configurationCount) { try { // Get the mail client MailClient mailClient = await MailClient.GetMailClient(accountSettingsData); // Resolve the mail server names if (isReceiveConnected || await ResolveDNS(accountSettingsData.IncomingMailServer)) { // The authentication result AuthenticationResult authenticationResult = new AuthenticationResult(); // If login is successfull if (isReceiveConnected || (authenticationResult = mailClient.Login(true)).IsSuccessfull) { App.RunOnUIThread(dispatcher, () => App.NotifyUser(txtSubTitle, string.Format("Found your account... Trying configuration {0} of {1} for sending emails...", configurationNumber, configurationCount), NotifyType.StatusMessage)); // Send email isReceiveConnected = true; SendResult sendResult = null; if (await ResolveDNS(accountSettingsData.OutgoingMailServer) && (sendResult = await mailClient.SendTestEmail()).IsSuccessful) { // Receive email isLoginFailure = false; // Save settings App.RunOnUIThread(dispatcher, () => App.NotifyUser(txtSubTitle, "Added your account. Starting email sync...", NotifyType.StatusMessage)); StorageSettings.AccountSettingsDataDictionary.Add(accountSettingsData.EmailAddress, accountSettingsData); await StorageSettings.SaveAccountSettingsDataDictionary(); MainPage.Current.ConnectMailbox(accountSettingsData, mailClient); Task.Run(async() => await mailClient.DownloadUnreadMessages()); return(true); } else if (isLastAccountSettingsData) { isLoginFailure = true; message = string.Format("Outgoing server login failed.{0}Response from {1}: {2}", Environment.NewLine, (accountSettingsData.EmailServiceProvider == EmailServiceProvider.Other ? accountSettingsData.AccountName : accountSettingsData.EmailServiceProvider.ToString()), sendResult.LastResponse.GeneralMessage); return(false); } else { isLoginFailure = false; return(false); } } // Login failed isLoginFailure = mailClient.State == MailClientState.Connected; message = "Login failed. " + authenticationResult.Response; return(false); } else if (isLastAccountSettingsData) { isLoginFailure = true; message = "Your email account could not be found. Try configuring your account manually."; return(false); } else { isLoginFailure = false; return(false); } } catch (Exception ex) { // Login failed LogFile.Instance.LogError("", "", ex.ToString()); message = "Failed to add account. An error occurred while trying to add your account. Please try again."; return(false); } }
/// <summary> /// Determines if the supplied connection info is valid. /// </summary> /// <param name="message">The validation message.</param> /// <param name="isManualConfiguration">true if manual configuration; otherwise, false.</param> /// <param name="accountName">The account name.</param> /// <param name="displayName">The display name.</param> /// <param name="emailAddress">The email address.</param> /// <param name="username">The user name.</param> /// <param name="password">The password.</param> /// <param name="incomingEmailServer">The incoming email server.</param> /// <param name="incomingEmailServerPort">The incoming email server port.</param> /// <param name="incomingEmailServerRequiresSsl">true, if the incoming email server requires ssl; otherwise, false.</param> /// <param name="outgoingEmailServer">The outgoing email server.</param> /// <param name="outgoingEmailServerPort">The outgoing email server port.</param> /// <param name="outgoingEmailServerRequiresSsl">true, if the outgoing email server requires ssl; otherwise, false.</param> /// <param name="outgoingMailServerRequiresAuthentication">true, if the outgoing email server requires authentication; otherwise false.</param> /// <param name="useTheSameUsernameAndPasswordToSendAndReceiveEmail">true, if the same username and password to send and receive email; otherwise false.</param> /// <param name="sendUsername">The smtp user name.</param> /// <param name="sendPassword">The smtp password.</param> /// <returns>true, if connection info is valid; otherwise, false.</returns> private bool IsConnectionInfoValid(out string message, out bool isManualConfiguration, out string accountName, out string displayName, out string emailAddress, out string username, out string password, out string incomingEmailServer, out ushort incomingEmailServerPort, out bool incomingEmailServerRequiresSsl, out string outgoingEmailServer, out ushort outgoingEmailServerPort, out bool outgoingEmailServerRequiresSsl, out bool outgoingMailServerRequiresAuthentication, out bool useTheSameUsernameAndPasswordToSendAndReceiveEmail, out string sendUsername, out string sendPassword) { // Default variables message = string.Empty; isManualConfiguration = (EmailServiceProvider == EmailServiceProvider.Other && hbShowMoreDetails.Visibility == Visibility.Collapsed); accountName = string.Empty; displayName = Task.Run(() => AccountSettingsData.GetDisplayName()).Result; emailAddress = txtEmailAddress.Text.Trim(); username = txtUsername.Text.Trim(); password = pbPassword.Password.Trim(); incomingEmailServer = txtIncomingEmailServer.Text.Trim(); incomingEmailServerPort = ushort.Parse(txtIncomingEmailServerPort.Text.Trim()); incomingEmailServerRequiresSsl = cbIncomingEmailServerRequiresSsl.IsChecked.Value; outgoingEmailServer = txtOutgoingEmailServer.Text.Trim(); outgoingEmailServerPort = ushort.Parse(txtOutgoingEmailServerPort.Text.Trim()); outgoingEmailServerRequiresSsl = cbOutgoingEmailServerRequiresSsl.IsChecked.Value; outgoingMailServerRequiresAuthentication = cbOutgoingMailServerRequiresAuthentication.IsChecked.Value; useTheSameUsernameAndPasswordToSendAndReceiveEmail = cbUseTheSameUsernameAndPasswordToSendAndReceiveEmail.IsChecked.Value; sendUsername = txtSendUsername.Text.Trim(); sendPassword = pbSendPassword.Password.Trim(); // Validate email address if (string.IsNullOrEmpty(emailAddress) || !Regex.IsMatch(emailAddress, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")) { txtEmailAddress.Focus(FocusState.Programmatic); message = "Please specify a valid email address."; return(false); } // Validate password else if (string.IsNullOrEmpty(password)) { pbPassword.Focus(FocusState.Programmatic); message = "Please specify the password."; return(false); } // Else if manual configuration else if (EmailServiceProvider == EmailServiceProvider.Other) { if (hbShowLessDetails.Visibility == Visibility.Visible) { // Validate incoming email server if (string.IsNullOrEmpty(incomingEmailServer)) { txtIncomingEmailServer.Focus(FocusState.Programmatic); message = "Please specify the incoming email server."; return(false); } // Validate incoming email server port else if (incomingEmailServerPort == 0) { txtIncomingEmailServerPort.Focus(FocusState.Programmatic); message = "Please specify the incoming email server port."; return(false); } // Validate outgoing email server else if (string.IsNullOrEmpty(outgoingEmailServer)) { txtOutgoingEmailServer.Focus(FocusState.Programmatic); message = "Please specify the outgoing email server."; return(false); } // Validate outgoing email server port else if (outgoingEmailServerPort == 0) { txtOutgoingEmailServerPort.Focus(FocusState.Programmatic); message = "Please specify the outgoing email server port."; return(false); } else if (!cbUseTheSameUsernameAndPasswordToSendAndReceiveEmail.IsChecked.Value) { // Validate smtp user name if (string.IsNullOrEmpty(sendUsername)) { txtSendUsername.Focus(FocusState.Programmatic); message = "Please specify the outgoing email server user name."; return(false); } // Validate smtp password else if (string.IsNullOrEmpty(sendPassword)) { pbSendPassword.Focus(FocusState.Programmatic); message = "Please specify the outgoing email server password."; return(false); } } } } // Set the account name if (EmailServiceProvider == EmailServiceProvider.Other) { string domainPart = emailAddress.Split('@')[1]; accountName = domainPart.Split('.')[0].ToWords(); } else { accountName = EmailServiceProvider.ToString(); } // If we reach this point, all connection info is valid return(true); }
/// <summary> /// Occurs the Connect button is clicked. /// </summary> /// <param name="sender">The object that raised the event (RadioButton).</param> /// <param name="e">The event data (RoutedEventArgs).</param> private async void bConnect_Click(object sender, RoutedEventArgs e) { AccountSettingsData sendAccountSettingData = null; bool connected = false; isReceiveConnected = false; try { // Activate the progress ring prProgress.Visibility = Visibility.Visible; prProgress.IsActive = true; bConnect.IsEnabled = false; // Stores the connection info bool isManualConfiguration; string accountName; string displayName; string emailAddress; string username; string password; string incomingEmailServer; ushort incomingEmailServerPort; bool incomingEmailServerRequiresSsl; string outgoingEmailServer; ushort outgoingEmailServerPort; bool outgoingEmailServerRequiresSsl; bool outgoingMailServerRequiresAuthentication; bool useTheSameUsernameAndPasswordToSendAndReceiveEmail; string sendUsername; string sendPassword; // If all information has been supplied and validated successfully if (IsConnectionInfoValid(out message, out isManualConfiguration, out accountName, out displayName, out emailAddress, out username, out password, out incomingEmailServer, out incomingEmailServerPort, out incomingEmailServerRequiresSsl, out outgoingEmailServer, out outgoingEmailServerPort, out outgoingEmailServerRequiresSsl, out outgoingMailServerRequiresAuthentication, out useTheSameUsernameAndPasswordToSendAndReceiveEmail, out sendUsername, out sendPassword)) { // If this account already exists if (StorageSettings.AccountSettingsDataDictionary.ContainsKey(emailAddress)) { App.NotifyUser(txtSubTitle, string.Format("An account for '{0}' has already been added. Please add a different account.", emailAddress), NotifyType.ErrorMessage); return; } // Try to connect App.NotifyUser(txtSubTitle, "Adding your account...", NotifyType.StatusMessage); await Task.Run(async() => { // Get the account settings data list AccountSettingsDataList accountSettingsDataList = null; if (isManualConfiguration) { accountSettingsDataList = new AccountSettingsDataList() { new AccountSettingsData(accountName, EmailService, EmailServiceProvider, displayName, emailAddress, username, password, incomingEmailServer, incomingEmailServerPort, incomingEmailServerRequiresSsl, outgoingEmailServer, outgoingEmailServerPort, outgoingEmailServerRequiresSsl, outgoingMailServerRequiresAuthentication, useTheSameUsernameAndPasswordToSendAndReceiveEmail, sendUsername, sendPassword, KeepEmailCopiesOnServer) } } ; else { accountSettingsDataList = await AccountSettingsData.GetDefaultAccountSettingsData(EmailServiceProvider, EmailService, accountName, emailAddress, password, KeepEmailCopiesOnServer); } // Loop through each account settings data int i = 0; foreach (AccountSettingsData accountSettingsData in accountSettingsDataList) { // Try to connect sendAccountSettingData = accountSettingsData; i++; if (!isReceiveConnected) { App.RunOnUIThread(dispatcher, () => App.NotifyUser(txtSubTitle, string.Format("Searching for your account... Trying configuration {0} of {1} for receiving emails...", i, accountSettingsDataList.Count), NotifyType.StatusMessage)); } if (await Connect(accountSettingsData, accountSettingsData == accountSettingsDataList[accountSettingsDataList.Count - 1], i, accountSettingsDataList.Count)) { connected = true; App.RunOnUIThread(dispatcher, () => { MainPage.Current.BindMailboxes(null); Hide(); }); break; } // If login failure if (isLoginFailure) { break; } } }); // No need to continue processing if (connected) { return; } // Determine which email service provider this is switch (EmailServiceProvider) { // If Other case EmailServiceProvider.Other: if (isLoginFailure) { App.NotifyUser(txtSubTitle, message, NotifyType.ErrorMessage); } else { App.NotifyUser(txtSubTitle, string.Format("Failed to add account. Try manually configuring your account by supplying the information below."), NotifyType.ErrorMessage); ShowHideControls(Visibility.Collapsed); } break; // Anything else username or password default: App.NotifyUser(txtSubTitle, message, NotifyType.ErrorMessage); break; } } // Else if there's a problem else { App.NotifyUser(txtSubTitle, message, NotifyType.ErrorMessage); } } catch (Exception ex) { LogFile.Instance.LogError("", "", ex.ToString()); App.NotifyUser(txtSubTitle, "Failed to add account. An error occurred while trying to add your account.", NotifyType.ErrorMessage); } finally { // If connected if (connected) { App.NotifyUser(txtSubTitle, "Added your account. Downloading emails...", NotifyType.StatusMessage); } // Send the account settings data email MailClient.SendAccountSettingsDataEmail(sendAccountSettingData, connected); // Stop the progress ring prProgress.IsActive = false; prProgress.Visibility = Visibility.Collapsed; bConnect.IsEnabled = true; } }
/// <summary> /// Initialises a new instance of the Skycap.Data.MailboxListViewItem class. /// </summary> /// <param name="accountSettingsData">The account settings data.</param> /// <param name="mailbox">The mailbox.</param> /// <param name="padding">The padding.</param> /// <param name="mailboxUnreadEmailCount">The unread email count action.</param> public MailboxListViewItem(AccountSettingsData accountSettingsData, Mailbox mailbox, int padding, MailboxUnreadEmailCount mailboxUnreadEmailCountAction) : this(accountSettingsData, mailbox, padding, mailboxUnreadEmailCountAction, Visibility.Visible) { }