Example #1
0
        private async void ButtonSend_Click(object sender, RoutedEventArgs e)
        {
            string errorDescription = string.Empty;

            try
            {
                await _doOauthAsync();

                TextStatus.Text = "Oauth is completed, ready to send email.";
            }
            catch (Exception ep)
            {
                errorDescription = string.Format("Failed to do oauth, exception: {0}", ep.Message);
            }

            if (!string.IsNullOrWhiteSpace(errorDescription))
            {
                await new MessageDialog(errorDescription).ShowAsync();
                TextStatus.Text = errorDescription;
                return;
            }

            if (string.IsNullOrWhiteSpace(TextTo.Text) && string.IsNullOrWhiteSpace(TextCc.Text))
            {
                MessageDialog dlg = new MessageDialog("Please input a recipient at least!");
                await dlg.ShowAsync();

                TextTo.Text = ""; TextCc.Text = "";
                TextTo.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                return;
            }

            if (string.IsNullOrWhiteSpace(TextServer.Text))
            {
                MessageDialog dlg = new MessageDialog("Please input server address!");
                await dlg.ShowAsync();

                TextServer.Text = "";
                TextServer.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                return;
            }

            ButtonSend.IsEnabled          = false;
            ProgressBarSending.Value      = 0;
            ProgressBarSending.Visibility = Visibility.Visible;
            PageViewer.ChangeView(0, PageViewer.ScrollableHeight, 1);
            this.Focus(FocusState.Programmatic);

            try
            {
                await _sendEmailAsync();
            }
            catch (Exception ep)
            {
                errorDescription = string.Format("Failed to do oauth, exception: {0}", ep.Message);
            }

            if (!string.IsNullOrWhiteSpace(errorDescription))
            {
                await new MessageDialog(errorDescription).ShowAsync();
                TextStatus.Text = errorDescription;
            }

            ProgressBarSending.Visibility = Visibility.Collapsed;
            _asyncCancel = null;

            ButtonSend.IsEnabled   = true;
            ButtonCancel.IsEnabled = false;
            ButtonClear.IsEnabled  = true;
        }
        private async void ButtonSend_Click(object sender, RoutedEventArgs e)
        {
            if (TextFrom.Text.Trim().Length == 0)
            {
                MessageDialog dlg = new MessageDialog("Please input from address!");
                await dlg.ShowAsync();

                TextFrom.Text = "";
                TextFrom.Focus(FocusState.Programmatic);
                return;
            }

            if (TextTo.Text.Trim().Length == 0 && TextCc.Text.Trim().Length == 0)
            {
                MessageDialog dlg = new MessageDialog("Please input a recipient at least!");
                await dlg.ShowAsync();

                TextTo.Text = ""; TextCc.Text = "";
                TextTo.Focus(FocusState.Programmatic);
                return;
            }

            if (TextServer.Text.Trim().Length == 0)
            {
                MessageDialog dlg = new MessageDialog("Please input server address!");
                await dlg.ShowAsync();

                TextServer.Text = "";
                TextServer.Focus(FocusState.Programmatic);
                return;
            }

            bool isAuthenticationRequired = CheckAuthentication.IsOn;

            if (isAuthenticationRequired)
            {
                if (TextUser.Text.Trim().Length == 0)
                {
                    MessageDialog dlg = new MessageDialog("Please input user name!");
                    await dlg.ShowAsync();

                    TextUser.Text = "";
                    TextUser.Focus(FocusState.Programmatic);
                    return;
                }

                if (TextPassword.Password.Trim().Length == 0)
                {
                    MessageDialog dlg = new MessageDialog("Please input password!");
                    await dlg.ShowAsync();

                    TextPassword.Password = "";
                    TextPassword.Focus(FocusState.Programmatic);
                    return;
                }
            }

            ButtonSend.IsEnabled          = false;
            ProgressBarSending.Value      = 0;
            ProgressBarSending.Visibility = Visibility.Visible;
            pageViewer.ChangeView(0, pageViewer.ScrollableHeight, 1);
            this.Focus(FocusState.Programmatic);

            try
            {
                var smtp = new SmtpClient();

                // add event handler
                smtp.Authorized        += OnAuthorized;
                smtp.Connected         += OnConnected;
                smtp.Securing          += OnSecuring;
                smtp.SendingDataStream += OnSendingDataStream;

                var   server = new SmtpServer(TextServer.Text);
                int[] ports  = { 25, 587, 465 };
                server.Port = ports[ListPorts.SelectedIndex];

                bool useSslConnection = CheckSsl.IsOn;
                if (useSslConnection)
                {
                    // use SSL/TLS based on server port
                    server.ConnectType = SmtpConnectType.ConnectSSLAuto;
                }
                else
                {
                    // Most mordern SMTP servers require SSL/TLS connection now
                    // ConnectTryTLS means if server supports SSL/TLS connection, SSL/TLS is used automatically
                    server.ConnectType = SmtpConnectType.ConnectTryTLS;
                }

                server.Protocol = (ServerProtocol)ListProtocols.SelectedIndex;
                if (isAuthenticationRequired)
                {
                    server.User     = TextUser.Text;
                    server.Password = TextPassword.Password;
                }

                // For evaluation usage, please use "TryIt" as the license code, otherwise the
                // "Invalid License Code" exception will be thrown. However, the trial object only can be used
                // with developer license

                // For licensed usage, please use your license code instead of "TryIt", then the object
                // can used with published windows store application.
                var mail = new SmtpMail("TryIt");

                mail.From = new MailAddress(TextFrom.Text);
                // If your Exchange Server is 2007 and used Exchange Web Service protocol, please add the following line;
                // oMail.Headers.RemoveKey("From");
                mail.To      = new AddressCollection(TextTo.Text);
                mail.Cc      = new AddressCollection(TextCc.Text);
                mail.Subject = TextSubject.Text;

                if (!CheckHtml.IsOn)
                {
                    mail.TextBody = TextEditor.Text;
                }
                else
                {
                    string html = await HtmlEditor.InvokeScriptAsync("getHtml", null);

                    html = "<html><head><meta charset=\"utf-8\" /></head><body style=\"font-family:Calibri;font-size: 15px;\">" + html + "<body></html>";
                    await mail.ImportHtmlAsync(html,
                                               Windows.ApplicationModel.Package.Current.InstalledLocation.Path,
                                               ImportHtmlBodyOptions.ErrorThrowException | ImportHtmlBodyOptions.ImportLocalPictures
                                               | ImportHtmlBodyOptions.ImportHttpPictures | ImportHtmlBodyOptions.ImportCss);
                }

                int count = _attachments.Count;
                for (int i = 0; i < count; i++)
                {
                    await mail.AddAttachmentAsync(_attachments[i]);
                }

                ButtonCancel.IsEnabled = true;
                TextStatus.Text        = string.Format("Connecting {0} ...", server.Server);
                // You can genereate a log file by the following code.
                // smtp.LogFileName = "ms-appdata:///local/smtp.txt";
                _asyncCall = smtp.SendMailAsync(server, mail);
                await _asyncCall;

                TextStatus.Text = "Completed";
            }
            catch (Exception ep)
            {
                TextStatus.Text = "Error:  " + ep.Message.TrimEnd("\r\n".ToArray());
            }

            ProgressBarSending.Visibility = Visibility.Collapsed;

            _asyncCall             = null;
            ButtonSend.IsEnabled   = true;
            ButtonCancel.IsEnabled = false;
        }
Example #3
0
        private async void ButtonSend_Click(object sender, RoutedEventArgs e)
        {
            _total = 0; _success = 0; _failed = 0;
            if (TextFrom.Text.Trim().Length == 0)
            {
                MessageDialog dlg = new MessageDialog("Please input from address!");
                await dlg.ShowAsync();

                TextFrom.Text = "";
                TextFrom.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                return;
            }

            if (TextTo.Text.Trim("\r\n \t".ToCharArray()).Length == 0)
            {
                MessageDialog dlg = new MessageDialog("Please input a recipient at least!");
                await dlg.ShowAsync();

                TextTo.Text = "";
                TextTo.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                return;
            }

            if (TextServer.Text.Trim().Length == 0)
            {
                MessageDialog dlg = new MessageDialog("Please input server address!");
                await dlg.ShowAsync();

                TextServer.Text = "";
                TextServer.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                return;
            }

            bool isUserAuthencation = CheckAuthentication.IsOn;

            if (isUserAuthencation)
            {
                if (TextUser.Text.Trim().Length == 0)
                {
                    MessageDialog dlg = new MessageDialog("Please input user name!");
                    await dlg.ShowAsync();

                    TextUser.Text = "";
                    TextUser.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                    return;
                }

                if (TextPassword.Password.Trim().Length == 0)
                {
                    MessageDialog dlg = new MessageDialog("Please input password!");
                    await dlg.ShowAsync();

                    TextPassword.Password = "";
                    TextPassword.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                    return;
                }
            }

            ButtonSend.IsEnabled    = false;
            ButtonSend.Visibility   = Visibility.Collapsed;
            ButtonCancel.Visibility = Visibility.Visible;
            ButtonCancel.IsEnabled  = true;
            ButtonClose.Visibility  = Visibility.Collapsed;
            ButtonClose.IsEnabled   = false;
            ButtonAttach.Visibility = Visibility.Collapsed;

            ListRecipients.Items.Clear();
            PageViewer.Visibility   = Visibility.Collapsed;
            StatusViewer.Visibility = Visibility.Visible;

            _cancellationToken = new CancellationTokenSource();

            List <Task> tasks = new List <Task>();

            string[]      toLines    = TextTo.Text.Trim("\r\n \t".ToCharArray()).Split("\n".ToCharArray());
            List <string> recipients = new List <string>();

            for (int i = 0; i < toLines.Length; i++)
            {
                string address = toLines[i].Trim("\r\n \t".ToCharArray());
                if (address.Length > 0)
                {
                    recipients.Add(address);
                }
            }

            int n = recipients.Count;

            toLines = recipients.ToArray();

            _total          = n;
            TextStatus.Text = string.Format("Total {0}, success: {1}, failed {2}",
                                            _total, _success, _failed);

            ButtonCancel.IsEnabled = true;

            n = 0;
            ListRecipients.Items.Add(new RecipientData("Email", "Status", 0));
            n++;
            for (int i = 0; i < toLines.Length; i++)
            {
                int maxThreads = (int)WorkerThreads.Value;
                while (tasks.Count >= maxThreads)
                {
                    Task[] currentTasks = tasks.ToArray();
                    Task   taskFinished = await Task.WhenAny(currentTasks);

                    tasks.Remove(taskFinished);

                    TextStatus.Text = string.Format(
                        "Total {0}, success: {1}, failed {2}",
                        _total, _success, _failed
                        );
                }

                string addr  = toLines[i];
                int    index = n;
                ListRecipients.Items.Add(new RecipientData(addr, "Queued", n));

                if (_cancellationToken.Token.IsCancellationRequested)
                {
                    n++;
                    UpdateRecipientItem(index, "Operation was cancelled!");
                    continue;
                }

                SmtpServer server = new SmtpServer(TextServer.Text);
                int[]      ports  = new int[] { 25, 587, 465 };
                server.Port = ports[ListPorts.SelectedIndex];

                bool isSslConnection = CheckSsl.IsOn;
                if (isSslConnection)
                {
                    // use SSL/TLS based on server port
                    server.ConnectType = SmtpConnectType.ConnectSSLAuto;
                }
                else
                {
                    // Most mordern SMTP servers require SSL/TLS connection now
                    // ConnectTryTLS means if server supports SSL/TLS connection, SSL/TLS is used automatically
                    server.ConnectType = SmtpConnectType.ConnectTryTLS;
                }

                server.Protocol = (ServerProtocol)ListProtocols.SelectedIndex;
                if (isUserAuthencation)
                {
                    server.User     = TextUser.Text;
                    server.Password = TextPassword.Password;
                }

                // For evaluation usage, please use "TryIt" as the license code, otherwise the
                // "Invalid License Code" exception will be thrown. However, the trial object only can be used
                // with developer license

                // For licensed usage, please use your license code instead of "TryIt", then the object
                // can used with published windows store application.
                SmtpMail mail = new SmtpMail("TryIt");

                mail.From = new MailAddress(TextFrom.Text);
                // If your Exchange Server is 2007 and used Exchange Web Service protocol, please add the following line;
                // oMail.Headers.RemoveKey("From");
                mail.To      = new AddressCollection(addr);
                mail.Subject = TextSubject.Text;

                string bodyText = "";
                bool   htmlBody = false;
                if (CheckHtml.IsOn)
                {
                    bodyText = await HtmlEditor.InvokeScriptAsync("getHtml", null);

                    htmlBody = true;
                }
                else
                {
                    bodyText = TextEditor.Text;
                }

                int      count       = _attachments.Count;
                string[] attachments = new string[count];
                for (int x = 0; x < count; x++)
                {
                    attachments[x] = _attachments[x];
                }

                Task task = Task.Factory.StartNew(() =>
                                                  SubmitMail(server, mail, attachments, bodyText, htmlBody, index).Wait()
                                                  );

                tasks.Add(task);
                n++;
            }

            if (tasks.Count > 0)
            {
                await Task.WhenAll(tasks.ToArray());
            }

            TextStatus.Text = string.Format("Total {0}, success: {1}, failed {2}",
                                            _total, _success, _failed);

            ButtonSend.IsEnabled    = false;
            ButtonSend.Visibility   = Visibility.Collapsed;
            ButtonCancel.Visibility = Visibility.Collapsed;
            ButtonCancel.IsEnabled  = false;
            ButtonClose.Visibility  = Visibility.Visible;
            ButtonClose.IsEnabled   = true;
            ButtonAttach.Visibility = Visibility.Collapsed;
        }