Exemple #1
0
        private async Task SubmitMail(
            SmtpServer server, SmtpMail mail, string[] attachments,
            string bodyText, bool htmlBody, int index)
        {
            SmtpClient smtp = null;

            try
            {
                smtp = new SmtpClient();

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

                UpdateRecipientItem(index, "Preparing ...");

                if (!htmlBody)
                {
                    mail.TextBody = bodyText;
                }
                else
                {
                    string html = bodyText;
                    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.Length;
                for (int i = 0; i < count; i++)
                {
                    await mail.AddAttachmentAsync(attachments[i]);
                }

                UpdateRecipientItem(index, string.Format("Connecting {0} ...", server.Server));
                smtp.Tag = index;

                // You can genereate a log file by the following code.
                // smtp.LogFileName = "ms-appdata:///local/smtp.txt";

                IAsyncAction asynCancelSend = smtp.SendMailAsync(server, mail);
                _cancellationToken.Token.Register(() => asynCancelSend.Cancel());
                await asynCancelSend;

                Interlocked.Increment(ref _success);
                UpdateRecipientItem(index, "Completed");
            }
            catch (Exception ep)
            {
                smtp.Close();
                string errDescription = ep.Message;
                UpdateRecipientItem(index, errDescription);
                Interlocked.Increment(ref _failed);
            }
        }
Exemple #2
0
        private async void SendMailToStaff(string room, string description, string filename)
        {
            try
            {
                SmtpClient client      = new SmtpClient();
                SmtpMail   mail        = new SmtpMail("Porocilo o škodi");
                SmtpServer mail_server = new SmtpServer("smtp.live.com");
                Attachment a           = new Attachment();
                mail.From = new MailAddress("*****@*****.**");

                Parallel.Invoke(
                    () =>
                {
                    mail.To.Add("*****@*****.**");
                    mail.Subject  = "V prostoru " + room + " je nastala škoda: ";
                    mail.TextBody = description;
                },
                    () =>
                {
                    mail_server.Port        = 25;
                    mail_server.Password    = "******";
                    mail_server.User        = "******";
                    mail_server.ConnectType = SmtpConnectType.ConnectSTARTTLS;
                });

                await mail.AddAttachmentAsync(filename);

                await client.SendMailAsync(mail_server, mail);

                Result = "Obvestilo uspesno poslano!";
            }
            catch (Exception e)
            {
                e      = Ex; Success = false;
                Result = "Zgodila se je napaka";
            }
        }
        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;
        }
Exemple #4
0
        private async Task _sendEmailAsync()
        {
            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 = new int[] { 25, 587, 465 };
            server.Port        = ports[ListPorts.SelectedIndex];
            server.ConnectType = SmtpConnectType.ConnectSSLAuto;

            server.Protocol = ServerProtocol.SMTP;
            if (ListProviders.SelectedIndex == OauthProvider.MsOffice365Provider)
            {
                server.Protocol = ServerProtocol.ExchangeEWS;
            }

            server.User     = _oauthWrapper.Provider.UserEmail;
            server.Password = _oauthWrapper.Provider.AccessToken;
            server.AuthType = SmtpAuthType.XOAUTH2;

            // 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(_oauthWrapper.Provider.UserEmail);
            var replyTo = new MailAddress(TextFrom.Text);

            if (string.Compare(replyTo.Address, _oauthWrapper.Provider.UserEmail, StringComparison.OrdinalIgnoreCase) != 0)
            {
                mail.ReplyTo = 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.
            // oSmtp.LogFileName = "ms-appdata:///local/smtp.txt";
            _asyncCancel = smtp.SendMailAsync(server, mail);
            await _asyncCancel;

            TextStatus.Text = "Completed";
        }
Exemple #5
0
        private async void btnSend_Tapped(object sender, TappedRoutedEventArgs e)
        {
            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().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(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 bAuth = (chkAuth.IsChecked.HasValue) ? (bool)chkAuth.IsChecked : false;
            if (bAuth)
            {
                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;
                }
            }

            btnSend.IsEnabled = false;
            pgBar.Value = 0;

            try
            {
                SmtpClient oSmtp = new SmtpClient();

                oSmtp.Authorized +=  OnAuthorized;
                oSmtp.Connected += OnConnected;
                oSmtp.Securing +=  OnSecuring;
                oSmtp.SendingDataStream += OnSendingDataStream;

                SmtpServer oServer = new SmtpServer(textServer.Text);
                bool bSSL = (chkSSL.IsChecked.HasValue) ? (bool)chkSSL.IsChecked : false;
                if (bSSL)
                {
                    oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
                }

                oServer.Protocol = (ServerProtocol)lstProtocols.SelectedIndex;

                if (bAuth)
                {
                    oServer.User = textUser.Text;
                    oServer.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 oMail = new SmtpMail("TryIt");

                oMail.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");
                oMail.To = new AddressCollection(textTo.Text);
                oMail.Cc = new AddressCollection(textCc.Text);
                oMail.Subject = textSubject.Text;

                if (lstFormat.SelectedIndex == 0)
                {
                    oMail.TextBody = textBody.Text;
                }
                else
                {
                    if (chkHtml.IsChecked.HasValue)
                    {
                        if ((bool)chkHtml.IsChecked)
                        {
                            editorMenu.Visibility = Windows.UI.Xaml.Visibility.Visible;
                            await htmlEditor.InvokeScriptAsync("OnViewHtmlSource", new string[] { "false" });
                            chkHtml.IsChecked = true;
                        }
                    }
                    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 oMail.ImportHtmlAsync(html,
                        Windows.ApplicationModel.Package.Current.InstalledLocation.Path,
                        ImportHtmlBodyOptions.ErrorThrowException | ImportHtmlBodyOptions.ImportLocalPictures
                        | ImportHtmlBodyOptions.ImportHttpPictures | ImportHtmlBodyOptions.ImportCss);
                }

                int count = m_atts.Count;
                for (int i = 0; i < count; i++)
                {
                    await oMail.AddAttachmentAsync(m_atts[i]);
                }
                btnCancel.IsEnabled = true;

                textStatus.Text = String.Format("Connecting {0} ...", oServer.Server);
                // You can genereate a log file by the following code.
                // oSmtp.LogFileName = "ms-appdata:///local/smtp.txt";
                asyncCancel = oSmtp.SendMailAsync(oServer, oMail);
                await asyncCancel;

                textStatus.Text = "Completed";

            }
            catch (Exception ep)
            {
                textStatus.Text = "Error:  " + ep.Message;
            }

            asyncCancel = null;
            btnSend.IsEnabled = true;
            btnCancel.IsEnabled = false;
        }
Exemple #6
0
        private async Task SubmitMail(
             SmtpServer oServer, SmtpMail oMail, string[] atts,
             string bodyText, bool htmlBody, int index )
        {
           
            SmtpClient oSmtp = null;
            try
            {
                oSmtp = new SmtpClient();
               // oSmtp.TaskCancellationToken = m_cts.Token;
               // oSmtp.Authorized += new SmtpClient.OnAuthorizedEventHandler(OnAuthorized);
                oSmtp.Connected += OnConnected;
              //  oSmtp.Securing += new SmtpClient.OnSecuringEventHandler(OnSecuring);
                //oSmtp.SendingDataStream +=
                  //  new SmtpClient.OnSendingDataStreamEventHandler(OnSendingDataStream);

                UpdateRecipientItem(index, "Preparing ...");
               
                if ( !htmlBody )
                {
                    oMail.TextBody = bodyText;
                }
                else
                {
                    string html = bodyText;
                    html = "<html><head><meta charset=\"utf-8\" /></head><body style=\"font-family:Calibri;font-size: 15px;\">" + html + "<body></html>";
                    await oMail.ImportHtmlAsync(html,
                        Windows.ApplicationModel.Package.Current.InstalledLocation.Path,
                        ImportHtmlBodyOptions.ErrorThrowException | ImportHtmlBodyOptions.ImportLocalPictures
                        | ImportHtmlBodyOptions.ImportHttpPictures | ImportHtmlBodyOptions.ImportCss);
                }

                int count = atts.Length;
                for (int i = 0; i < count; i++)
                {
                    await oMail.AddAttachmentAsync(atts[i]);
                }


                UpdateRecipientItem(index, String.Format("Connecting {0} ...", oServer.Server));
                oSmtp.Tag = index;

                // You can genereate a log file by the following code.
                // oSmtp.LogFileName = "ms-appdata:///local/smtp.txt";

                IAsyncAction asynCancelSend = oSmtp.SendMailAsync(oServer, oMail);
                m_cts.Token.Register(() => asynCancelSend.Cancel());
                await asynCancelSend;

                Interlocked.Increment(ref m_success);
                UpdateRecipientItem(index, "Completed");

            }
           catch (Exception ep)
            {
                oSmtp.Close();
                string errDescription = ep.Message;
                UpdateRecipientItem(index, errDescription);
                Interlocked.Increment(ref m_failed);
            }

        }
Exemple #7
0
        public static async Task Send_Email(string from, string password, string to, string subj, string body, string filePath)
        {
            String Result = "";
            try
            {
                SmtpMail oMail = new SmtpMail("TryIt");
                SmtpClient oSmtp = new SmtpClient();

                // Set sender email address, please change it to yours
                oMail.From = new MailAddress(from);

                // Add recipient email address, please change it to yours
                oMail.To.Add(new MailAddress(to));

                // Add attachment
                Attachment oAttachment = await oMail.AddAttachmentAsync(filePath);

                // Set email subject and email body text
                oMail.Subject = subj;
                oMail.TextBody = body;

                if (!getSMTPserver(from).Equals(""))
                {
                    // Your SMTP server address
                    SmtpServer oServer = new SmtpServer(getSMTPserver(from));

                    // User and password for SMTP authentication            
                    oServer.User = from;
                    oServer.Password = password;

                    // If your SMTP server requires TLS connection on 25 port, please add this line
                    // oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                    // If your SMTP server requires SSL connection on 465 port, please add this line
                    oServer.Port = 465;
                    oServer.ConnectType = SmtpConnectType.ConnectSSLAuto; // or SmtpConnectType.ConnectDirectSSL;

                    await oSmtp.SendMailAsync(oServer, oMail);
                    Result = "Email was sent successfully!";
                }
                else
                {
                    Result = "Host not found";
                }
            }
            catch (Exception ep)
            {
                Result = String.Format("Failed to send email with the following error: {0}", ep.Message);
                if (ep.Message.Contains("Password"))
                {
                    Result = "Failed to send Email: Incorrect Username or Password";
                }
                if (ep.Message.Contains("such host"))
                {
                    Result = "Failed to send Email: No Internet Connection";
                }
            }

            // Display Result by Diaglog box
            Windows.UI.Popups.MessageDialog dlg = new
                Windows.UI.Popups.MessageDialog(Result);

            await dlg.ShowAsync();
        }