Beispiel #1
0
        public void SendWait(EmailMessage email)
        {
            SmtpClient client = new SmtpClient(Host, Port)
            {
                UseDefaultCredentials = false,
                Credentials           = new NetworkCredential(Username, Password),
                DeliveryMethod        = SmtpDeliveryMethod.Network,
                EnableSsl             = Ssl
            };
            // client.Timeout = Timeout * 1000; // Ignored for Async

            // The userState can be any object that allows your callback
            // method to identify this send operation.
            // For this example, the userToken is a string constant.
            string userState = email.Subject;

            // Set the method that is called back when the send operation ends.
            client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);

            int ms = 250; // 1/4 second to sleep

            // Create an AutoResetEvent to signal the timeout threshold in the
            // timer callback has been reached.
            var autoEvent     = new AutoResetEvent(false);
            var statusChecker = new StatusChecker(Timeout * 1000 / ms);

            // Create a timer that invokes CheckStatus after ms and every ms thereafter.
            // Console.WriteLine("{0:h:mm:ss.fff} Creating timer.\n", DateTime.Now);
            var stateTimer = new Timer(statusChecker.CheckStatus, autoEvent, ms, ms);

            Console.WriteLine("Sending message... wait {0} sec or press Esc to cancel.", Timeout);

            client.SendAsync(email, userState);

            // When autoEvent signals time is out, dispose of the timer.
            autoEvent.WaitOne();
            stateTimer.Dispose();
            if (statusChecker.Canceled)
            {
                client.SendAsyncCancel();
                Trace.TraceWarning("Отправка прервана пользователем.");
            }
            else if (statusChecker.TimedOut)
            {
                client.SendAsyncCancel();
                Trace.TraceWarning("Отправка прервана по таймауту.");
            }
            // Clean up.
            email.Dispose();
        }
Beispiel #2
0
        public static void  sendemail()
        {
            // Command-line argument must be the SMTP host.
            SmtpClient  client  = new SmtpClient();
            MailMessage message = new MailMessage();

            client.Port = 25;

            client.DeliveryMethod        = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;

            client.Host  = "smtp.gmail.com";
            message.Body = "This is a test email message sent by an application. ";



            Console.WriteLine("sending Message...press c to cancel. press any other button to exit");

            string input = Console.ReadLine();

            // then cancel the pending operation.
            if (input.StartsWith("c") && mailSent == false)
            {
                Console.WriteLine("canceling send");
                client.SendAsyncCancel();
            }
            // Clean up.

            Console.WriteLine("Goodbye.");
        }
Beispiel #3
0
 /// <summary>
 /// 取消异步发送,和SendAsync对应
 /// </summary>
 public void SendAsyncCancel()
 {
     if (smtpClient != null)
     {
         smtpClient.SendAsyncCancel();
     }
 }
Beispiel #4
0
        public static void Main(string correo, string clave)
        {
            SmtpClient  client = new SmtpClient();
            MailAddress from   = new MailAddress("*****@*****.**",
                                                 "Jane " + (char)0xD8 + " Clayton",
                                                 System.Text.Encoding.UTF8);
            MailAddress to      = new MailAddress(correo);
            MailMessage message = new MailMessage(from, to);

            message.Body = "This is a test e-mail message sent by an application. ";
            string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });

            message.Body           += Environment.NewLine + someArrows;
            message.BodyEncoding    = System.Text.Encoding.UTF8;
            message.Subject         = "Clave" + clave + someArrows;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            client.SendCompleted   += new
                                      SendCompletedEventHandler(SendCompletedCallback);
            string userState = "test message1";

            client.SendAsync(message, userState);
            Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
            string answer = Console.ReadLine();

            if (answer.StartsWith("c") && mailSent == false)
            {
                client.SendAsyncCancel();
            }
            message.Dispose();
            Console.WriteLine("Goodbye.");
        }
 //送信キャンセル処理
 private void bt_Cansel_Click(object sender, RoutedEventArgs e)
 {
     if (sc != null)
     {
         sc.SendAsyncCancel();
     }
 }
Beispiel #6
0
 /// <summary>
 /// 取消电子邮件异步发送事件
 /// </summary>
 public void SendAsyncCancel()
 {
     if (null != FSmtpClient)
     {
         FSmtpClient.SendAsyncCancel();
     }
 }
Beispiel #7
0
        public static async Task SendMailAsync(
            this SmtpClient client, MailMessage message, CancellationToken cancellationToken)
        {
            var       ctsWrapper = new[] { cancellationToken.CreateLinkedSource() };
            var       mailSent   = false;
            Exception?exception  = null;

            void onCompleted(object sender, AsyncCompletedEventArgs e)
            {
                if (e.Cancelled)
                {
                    exception = new TaskCanceledException();
                }

                if (e.Error != null)
                {
                    exception = e.Error;
                }

                mailSent = true;
                ctsWrapper[0].Cancel();
            };

            client.SendCompleted += onCompleted;
            client.SendAsync(message, new object());

            try
            {
                await Task.Delay(Timeout.InfiniteTimeSpan, ctsWrapper[0].Token);
            }
            catch (TaskCanceledException)
            {
                // no throw for canceled delay
            }

            if (!mailSent)
            {
                ctsWrapper[0] = new CancellationTokenSource();
                client.SendAsyncCancel();

                try
                {
                    await Task.Delay(TimeSpan.FromSeconds(1), ctsWrapper[0].Token);

                    Debug.Fail(string.Empty);
                    throw new InvalidOperationException();
                }
                catch (TaskCanceledException)
                {
                    // no throw for canceled delay
                }
            }

            client.SendCompleted -= onCompleted;

            if (exception != null)
            {
                throw exception;
            }
        }
Beispiel #8
0
        private static void send1()
        {
            // Command line argument must the the SMTP host.
            SmtpClient client = new SmtpClient("localhost");
            // Specify the e-mail sender.
            // Create a mailing address that includes a UTF8 character
            // in the display name.

            MailAddress from = new MailAddress("*****@*****.**", "", System.Text.Encoding.UTF8);
            // Set destinations for the e-mail message.
            MailAddress to = new MailAddress("*****@*****.**");
            // Specify the message content.

            MailMessage message = new MailMessage(from, to);

            message.Body          = "afad";
            message.Subject       = "aasfd";
            client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback1);

            string userState = "test message1";

            client.SendAsync(message, userState);
            Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
            string answer = Console.ReadLine();

            // If the user canceled the send, and mail hasn't been sent yet,
            // then cancel the pending operation.
            if (answer.StartsWith("c") && mailSent == false)
            {
                client.SendAsyncCancel();
            }
            // Clean up.
            message.Dispose();
        }
 //送信キャンセル
 private void CancelButton_Click(object sender, RoutedEventArgs e)
 {
     if (sc == null)
     {
         sc.SendAsyncCancel();
     }
 }
Beispiel #10
0
 public void CancelMessageSend()
 {
     if (_mailSent == false && client != null)
     {
         client.SendAsyncCancel();
     }
 }
Beispiel #11
0
        /// <summary>
        /// 取消异步邮件发送
        /// </summary>
        public void SendAsyncCancel()
        {
            // 因为此类为非线程安全类,所以 SendAsyncCancel 和发送邮件方法中操作MessageQueue部分的代码肯定是串行化的。
            // 所以不存在一边入队,一边出队导致无法完全取消所有邮件发送

            // 1、清空队列。
            // 2、取消正在异步发送的mail。
            // 3、设置计划数量=完成数量
            // 4、执行 AutoDisposeSmtp()

            if (m_IsAsync)
            {
                // 1、清空队列。
                MailUserState tempMailUserState = null;
                while (MessageQueue.TryDequeue(out tempMailUserState))
                {
                    Interlocked.Decrement(ref m_messageQueueCount);
                    MailMessage message = tempMailUserState.CurMailMessage;
                    this.InnerDisposeMessage(message);
                }
                tempMailUserState = null;
                // 2、取消正在异步发送的mail。
                m_SmtpClient.SendAsyncCancel();
                // 3、设置计划数量=完成数量
                PrepareSendCount = CompletedSendCount;
                // 4、执行 AutoDisposeSmtp()
                this.AutoDisposeSmtp();
            }
            else
            {
                throw new Exception(MailValidatorHelper.EMAIL_ASYNC_CALL_ERROR);
            }
        }
Beispiel #12
0
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="mailMessage">邮件内容</param>
        public static async Task SendAsync(MailMessage mailMessage)
        {
            if (mailMessage == null)
            {
                throw new ArgumentNullException(nameof(mailMessage));
            }

            CheckSmtpServer();

            //检查有无发件人信息
            if (mailMessage.From != null)
            {
                if (mailMessage.From.Address != GlobalMailOptions.SmtpServerInfo.MailUserName)
                {
                    throw new ArgumentException("Can't support overwrite default sender");
                }
            }
            else
            {
                mailMessage.From = new MailAddress(GlobalMailOptions.SmtpServerInfo.MailUserName,
                                                   GlobalMailOptions.DefaultSenderDisplayerName, GlobalMailOptions.DefaultEncoding);
            }

            using var smtpClient = new SmtpClient
                  {
                      Host      = GlobalMailOptions.SmtpServerInfo.SmtpHost,
                      EnableSsl = GlobalMailOptions.EnableSsl
                  };

            if (GlobalMailOptions.SmtpServerInfo.Port != null)
            {
                smtpClient.Port = GlobalMailOptions.SmtpServerInfo.Port.Value;
            }
            else if (smtpClient.EnableSsl)
            {
                smtpClient.Port = 587;
            }

            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials           = new NetworkCredential(GlobalMailOptions.SmtpServerInfo.MailUserName,
                                                                     GlobalMailOptions.SmtpServerInfo.MailPassword);

            var sendMailAsync   = smtpClient.SendMailAsync(mailMessage);
            var delayTaskCancel = new CancellationTokenSource();
            var delayTask       = Task.Delay(GlobalMailOptions.DefaultTimeOut, delayTaskCancel.Token);

            if (await Task.WhenAny(sendMailAsync, delayTask) == delayTask)
            {
                //任务超时,取消发送
                smtpClient.SendAsyncCancel();

                //超时异常
                throw new OperationCanceledException("Send mail timeout");
            }
            else
            {
                delayTaskCancel.Cancel();
            }
        }
 public void CancelSendAsync()
 {
     // If mail hasn't been sent yet, then cancel the pending operation
     if (m_mailSent == false)
     {
         m_smtp.SendAsyncCancel();
     }
 }
Beispiel #14
0
        public static void Main(string[] args)
        {
            string xmstpapiJson = XsmtpapiHeaderAsJson();

            var client = new SmtpClient
            {
                Port                  = 587,
                Host                  = "smtp.sendgrid.net",
                Timeout               = 10000,
                DeliveryMethod        = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false
            };

            Console.WriteLine("Enter your SendGrid username:"******"Enter your SendGrid password (warning: password will be visible):");
            string password = Console.ReadLine();

            client.Credentials = new NetworkCredential(username, password);

            var mail = new MailMessage
            {
                From    = new MailAddress("*****@*****.**"),
                Subject = "Good Choice Signing Up for Our Service!.",
                Body    = "Hi there. Thanks for signing up for Appsterify.ly. It's disruptive! %tag%"
            };

            // add the custom header that we built above
            mail.Headers.Add("X-SMTPAPI", xmstpapiJson);
            mail.BodyEncoding = Encoding.UTF8;

            //async event handler
            client.SendCompleted += SendCompletedCallback;
            const string state = "test1";

            Console.WriteLine("Enter an email address to which a test email will be sent:");
            string email = Console.ReadLine();

            if (email != null)
            {
                // Remember that MIME To's are different than SMTPAPI Header To's!
                mail.To.Add(new MailAddress(email));
                client.SendAsync(mail, state);

                Console.WriteLine(
                    "Sending message... press c to cancel, or wait for completion. Press any other key to exit.");
                string answer = Console.ReadLine();

                if (answer != null && answer.StartsWith("c") && _mailSent == false)
                {
                    client.SendAsyncCancel();
                }
            }

            mail.Dispose();
        }
Beispiel #15
0
 private void button8_Click(object sender, EventArgs e)
 {
     try
     {
         client.SendAsyncCancel();
         MessageBox.Show("Отправка отменена");
     }
     catch { }
 }
Beispiel #16
0
 public static async Task SendMailExAsync(
     SmtpClient @this, MailMessage message,
     CancellationToken token = default(CancellationToken))
 {
     using (token.Register(() =>
                           @this.SendAsyncCancel(), useSynchronizationContext: false))
     {
         await @this.SendMailAsync(message);
     }
 }
        void SendReport(string subject, string body)
        {
            IProgressDialog progress = new ProgressDialog();

            progress.Comment     = "Report Sending... Please Wait...";
            progress.AllowCancel = true;
            progress.Show();


            SmtpClient client = new SmtpClient();

            try
            {
                client.Port                  = 587;
                client.Host                  = "smtp.gmail.com";
                client.EnableSsl             = true;
                client.Timeout               = 20000;
                client.DeliveryMethod        = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Credentials           = new System.Net.NetworkCredential("*****@*****.**", "konvolucio.a0832d");
                MailMessage mm = new MailMessage("*****@*****.**", "*****@*****.**", subject, body);
                mm.BodyEncoding = UTF8Encoding.UTF8;
                mm.DeliveryNotificationOptions = DeliveryNotificationOptions.None;
                client.SendAsync(mm, null);
            }
            catch (Exception ex)
            {
                progress.Comment = ex.Message;
                MessageBox.Show("Cant send report..." + ex.Message);
                progress.End();
            }

            client.SendCompleted += (o, e) =>
            {
                if (e.Cancelled)
                {
                    progress.Comment = "Cancelled by User...";
                }
                else if (e.Error != null)
                {
                    MessageBox.Show("Cant send report..." + e.Error.Message);
                    progress.Comment = e.Error.Message;
                }
                else
                {
                    progress.Comment = "Complete";
                }
                progress.End();
            };

            progress.UserCanceled += (o1, e1) =>
            {
                client.SendAsyncCancel();
            };
        }
Beispiel #18
0
        private static void SendMail(object mailAdress)
        {
            // Command line argument must the the SMTP host.
            //using ()
            //{
            SmtpClient client = new SmtpClient();

            client.Host           = "smtp.office365.com";                                                           //邮件服务器
            client.Port           = 587;                                                                            //smtp主机上的端口号,默认是25.
            client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;                                     //邮件发送方式:通过网络发送到SMTP服务器
            client.Credentials    = new System.Net.NetworkCredential("*****@*****.**", "Athena@BCI"); //凭证,发件人登录邮箱的用户名和密码
            client.EnableSsl      = true;
            // Specify the e-mail sender.
            // Create a mailing address that includes a UTF8 character
            // in the display name.
            MailAddress from = new MailAddress("*****@*****.**",
                                               "BeyondSoft",
                                               System.Text.Encoding.UTF8);
            // Set destinations for the e-mail message.
            MailAddress to = new MailAddress(mailAdress.ToString());
            // Specify the message content.
            MailMessage message = new MailMessage(from, to);

            message.Body = "This is a test e-mail message sent by an application. ";
            // Include some non-ASCII characters in body and subject.
            string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });

            message.Body           += Environment.NewLine + someArrows + Environment.NewLine + "Thanks," + Environment.NewLine + "Mingpu Wu";
            message.BodyEncoding    = System.Text.Encoding.UTF8;
            message.Subject         = "Multi-Thread Mail From BeyondSoft Athena";
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            message.Priority        = System.Net.Mail.MailPriority.High;
            // Set the method that is called back when the send operation ends.
            client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
            // The userState can be any object that allows your callback
            // method to identify this send operation.
            // For this example, the userToken is a string constant.
            string userState = "test message1";

            client.SendAsync(message, userState);
            Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
            string answer = Console.ReadLine();

            // If the user canceled the send, and mail hasn't been sent yet,
            // then cancel the pending operation.
            if (answer.StartsWith("c") && mailSent == false)
            {
                client.SendAsyncCancel();
            }
            //}
            // Clean up.
            message.Dispose();
            //Console.WriteLine("Goodbye.");
        }
Beispiel #19
0
 private void btnCancel_Click(object sender, EventArgs e)
 {
     if (timer1.Enabled == false)
     {
         smtp.SendAsyncCancel();
     }
     else
     {
         this.Close();
     }
 }
Beispiel #20
0
 private void buttonCancelDownload_Click(object sender, EventArgs e)
 {
     try
     {
         client.SendAsyncCancel();
         client.Dispose();
     }
     catch (Exception ex)
     {
         log.Info(ex.ToString());
     }
 }
        private static async Task SendMailExImplAsync(
            SmtpClient client,
            MailMessage message,
            CancellationToken token)
        {
            token.ThrowIfCancellationRequested();

            var tcs = new TaskCompletionSource <bool>();
            SendCompletedEventHandler handler = null;
            Action unsubscribe = () => client.SendCompleted -= handler;

            handler = async(_, e) =>
            {
                unsubscribe();

                // a hack to complete the handler asynchronously
                await Task.Yield();

                if (e.UserState != tcs)
                {
                    tcs.TrySetException(new InvalidOperationException("Unexpected UserState"));
                }
                else if (e.Cancelled)
                {
                    tcs.TrySetCanceled();
                }
                else if (e.Error != null)
                {
                    tcs.TrySetException(e.Error);
                }
                else
                {
                    tcs.TrySetResult(true);
                }
            };

            client.SendCompleted += handler;
            try
            {
                client.SendAsync(message, tcs);
                using (token.Register(() =>
                {
                    client.SendAsyncCancel();
                }, useSynchronizationContext: false))
                {
                    await tcs.Task;
                }
            }
            finally
            {
                unsubscribe();
            }
        }
Beispiel #22
0
        //turn on below
        //https://www.google.com/settings/security/lesssecureapps

        public static void Main(string[] args)
        {
            // Command line argument must the the SMTP host.
            // dummy email account will be closed next acadmic unit.
            SmtpClient client = new SmtpClient("smtp.gmail.com")
            {
                Port = 587,
                UseDefaultCredentials = false,
                EnableSsl             = true,
                DeliveryMethod        = SmtpDeliveryMethod.Network,
                Credentials           = new System.Net.NetworkCredential("*****@*****.**", "!Qosti932"),
                Timeout = 20000
            };
            // Specify the e-mail sender.
            // in the display name.
            MailAddress from = new MailAddress("*****@*****.**",
                                               "TeamHorus",
                                               System.Text.Encoding.UTF8);
            // Set destinations for the e-mail message.
            MailAddress to = new MailAddress(args[0]);
            // Specify the message content.
            MailMessage message = new MailMessage(from, to);

            message.Body            = "Pleae find the Android client at the following url: https://drive.google.com/file/d/0B-hJtziIY0dlYk43WDdqY3NxZ1U/view?usp=sharing. ";
            message.BodyEncoding    = System.Text.Encoding.UTF8;
            message.Subject         = "A link from TeamHorus";
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            // Set the method that is called back when the send operation ends.
            client.SendCompleted += new
                                    SendCompletedEventHandler(SendCompletedCallback);
            // The userState can be any object that allows your callback
            // method to identify this send operation.
            // For this example, the userToken is a string constant.
            string userState = "test message1";

            client.SendAsync(message, userState);
            Console.WriteLine("Please check your email for the download url... press c to cancel sending this mail. Press any other key to exit.");
            string answer = Console.ReadLine();

            // If the user canceled the send, and mail hasn't been sent yet,
            // then cancel the pending operation.
            if (answer.StartsWith("c") && mailSent == false)
            {
                client.SendAsyncCancel();
            }
            // Clean up.
            message.Dispose();
            Console.WriteLine("Goodbye.");
        }
Beispiel #23
0
        public static void Main(string[] args)
        {
            // Command-line argument must be the SMTP host.
            SmtpClient client = new SmtpClient(args[0]);
            // Specify the email sender.
            //<snippet2>
            // Create a mailing address that includes a UTF8 character
            // in the display name.
            MailAddress from = new MailAddress("*****@*****.**",
                                               "Jane " + (char)0xD8 + " Clayton",
                                               System.Text.Encoding.UTF8);
            //</snippet2>
            // Set destinations for the email message.
            MailAddress to = new MailAddress("*****@*****.**");
            // Specify the message content.
            //<snippet3>
            MailMessage message = new MailMessage(from, to);

            message.Body = "This is a test email message sent by an application. ";
            // Include some non-ASCII characters in body and subject.
            string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });

            message.Body           += Environment.NewLine + someArrows;
            message.BodyEncoding    = System.Text.Encoding.UTF8;
            message.Subject         = "test message 1" + someArrows;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            //</snippet3>
            // Set the method that is called back when the send operation ends.
            client.SendCompleted += new
                                    SendCompletedEventHandler(SendCompletedCallback);
            // The userState can be any object that allows your callback
            // method to identify this send operation.
            // For this example, the userToken is a string constant.
            string userState = "test message1";

            client.SendAsync(message, userState);
            Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
            string answer = Console.ReadLine();

            // If the user canceled the send, and mail hasn't been sent yet,
            // then cancel the pending operation.
            if (answer.StartsWith("c") && mailSent == false)
            {
                client.SendAsyncCancel();
            }
            // Clean up.
            message.Dispose();
            Console.WriteLine("Goodbye.");
        }
Beispiel #24
0
        public async Task <bool> SendEmail(string recipient)
        {
            Throw.IfNull(recipient, nameof(recipient));

            _logger.Debug($"{nameof(SendEmail)} has been called with recipient {recipient}.");

            var senderAddress    = new MailAddress(_settingsReader.Email);
            var recipientAddress = new MailAddress(recipient);
            var email            = new MailMessage(senderAddress, recipientAddress);

            if (_dataSource is null)
            {
                email.Subject = Sitecore.Globalization.Translate.Text(DictionaryKeys.EmailSubject);
                email.Body    = Sitecore.Globalization.Translate.Text(DictionaryKeys.EmailBody);
            }
            else
            {
                email.Subject    = _dataSource.Subject;
                email.Body       = $"{_dataSource.Styles} {_dataSource.Header} {_dataSource.Body}";
                email.IsBodyHtml = true;
            }

            using (var client = new SmtpClient())
            {
                client.Host = _settingsReader.Host;
                client.Port = _settingsReader.Port;
                client.UseDefaultCredentials = false;
                client.Credentials           = new NetworkCredential(
                    _settingsReader.Email,
                    _settingsReader.Password);
                client.EnableSsl = true;

                var sendingEmailTask = client.SendMailAsync(email);
                if (sendingEmailTask == await Task.WhenAny(sendingEmailTask, Task.Delay(TimeoutForConnecting)))
                {
                    await sendingEmailTask;

                    _logger.Info($"Welcoming email has been sent in {nameof(SendEmail)}.");

                    return(true);
                }

                _logger.Error($"Welcoming email has not been sent in {nameof(SendEmail)}.");

                client.SendAsyncCancel();

                return(false);
            }
        }
Beispiel #25
0
        /// <summary>
        /// Asynchronosly sends a mail message via SmtpClient, but with a timeout
        /// </summary>
        /// <param name="client">SmtpClient</param>
        /// <param name="message">Message</param>
        /// <param name="timeout">Timeout</param>
        /// <returns>true, if the message is send within the timeout</returns>
        private bool SendMailAsync(SmtpClient client, MailMessage message, TimeSpan timeout)
        {
            ManualResetEvent trigger = new ManualResetEvent(false);

            client.SendAsync(message, trigger);
            try
            {
                return(trigger.WaitOne((int)timeout.TotalMilliseconds));
            }
            catch (TimeoutException)
            {
                client.SendAsyncCancel();
            }
            return(false);
        }
Beispiel #26
0
        public void Launch()
        {
            // Command-line argument must be the SMTP host.
            SmtpClient client = new SmtpClient("smtp.gmail.com")
            {
                Port        = 587,
                Credentials = new NetworkCredential(Credentials.Username, Credentials.Pwd),
                EnableSsl   = true,
            };

            MailAddress from = new MailAddress("*****@*****.**",
                                               "Jane " + (char)0xD8 + " Clayton",
                                               System.Text.Encoding.UTF8);

            MailAddress to      = new MailAddress("*****@*****.**");
            MailMessage message = new MailMessage(from, to);

            message.Body = "This is a test email message sent by an application. ";

            string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });

            // message.Body += Environment.NewLine + someArrows;
            message.Body        += Environment.NewLine + "Hello from Vlad";
            message.BodyEncoding = System.Text.Encoding.UTF8;
            // message.Subject = "test message 1" + someArrows;
            message.Subject         = "test message 1" + someArrows;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            client.SendCompleted   += new SendCompletedEventHandler(SendCompletedCallback);

            // The userState can be any object that allows your callback
            // method to identify this send operation.
            // For this example, the userToken is a string constant.
            string userState = "test message1";

            client.SendAsync(message, userState);


            Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
            string answer = Console.ReadLine();

            if (answer.StartsWith("c") && mailSent == false)
            {
                client.SendAsyncCancel();
            }
            // Clean up.
            message.Dispose();
            Console.WriteLine("Goodbye.");
        }
Beispiel #27
0
        private static void send2()
        {
            // Command line argument must the the SMTP host.
            SmtpClient client = new SmtpClient("localhost");
            // Specify the e-mail sender.
            // Create a mailing address that includes a UTF8 character
            // in the display name.

            MailAddress from = new MailAddress("*****@*****.**", "", System.Text.Encoding.UTF8);
            // Set destinations for the e-mail message.
            MailAddress to = new MailAddress("*****@*****.**");
            // Specify the message content.

            MailMessage message = new MailMessage(from, to);



            message.IsBodyHtml = true;
            message.Body       = Environment.NewLine + "<a href=#>This is a test e-mail message sent by an application. ";
            // Include some non-ASCII characters in body and subject.
            string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });

            message.Body           += Environment.NewLine + someArrows;
            message.Body           += Environment.NewLine;
            message.BodyEncoding    = System.Text.Encoding.UTF8;
            message.Subject         = "test message 1" + someArrows;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            // Set the method that is called back when the send operation ends.
            client.SendCompleted += new
                                    SendCompletedEventHandler(SendCompletedCallback2);
            // The userState can be any object that allows your callback
            // method to identify this send operation.
            // For this example, the userToken is a string constant.
            string userState = "test message1";

            client.SendAsync(message, userState);
            Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
            string answer = Console.ReadLine();

            // If the user canceled the send, and mail hasn't been sent yet,
            // then cancel the pending operation.
            if (answer.StartsWith("c") && mailSent == false)
            {
                client.SendAsyncCancel();
            }
            // Clean up.
            message.Dispose();
        }
Beispiel #28
0
        public async Task <bool> SendCommentEmail(CommentCreateRequest request)
        {
            var post = _dataProvider.GetPostById(request.PostId);
            var user = _dataProvider.GetUserById(post.UserId);
            var blog = _dataProvider.GetBlog();

            if (!string.IsNullOrWhiteSpace(blog.SmtpPassword))
            {
                blog.SmtpPassword = _protector.Unprotect(blog.SmtpPassword);
            }

            var response = true;

            try
            {
                using (var client = new SmtpClient
                {
                    Credentials = new NetworkCredential(blog.SmtpUsername, blog.SmtpPassword),
                    EnableSsl = blog.SmtpUseSsl,
                    Host = blog.SmtpHost,
                    Port = int.Parse(blog.SmtpPort),
                    Timeout = 10000
                })
                {
                    var sendMailTask = client.SendMailAsync(user.Email, user.Email,
                                                            $"{blog.EmailPrefix} Comment on post '{post.Title}'",
                                                            $"Comment by: {request.AuthorName} - {request.AuthorEmail}\n" +
                                                            $"Comment: {request.Text}");

                    if (await Task.WhenAny(sendMailTask, Task.Delay(5000)) == sendMailTask)
                    {
                        response = true;
                    }
                    else
                    {
                        // sendMailTask task timed out
                        client.SendAsyncCancel();
                        response = false;
                    }
                }
            }
            catch
            {
                response = false;
            }
            return(response);
        }
Beispiel #29
0
        static void Main(string[] args)
        {
            // Command-line argument must be the SMTP host.
            SmtpClient client = new SmtpClient("localhost", 2500);

            // Specify the email sender.
            // Create a mailing address that includes a UTF8 character
            // in the display name.
            MailAddress from = new MailAddress("*****@*****.**", "Test Person", System.Text.Encoding.UTF8);

            // Set destinations for the email message.
            MailAddress to = new MailAddress(args[0]);

            // Specify the message content.
            MailMessage message = new MailMessage(from, to);

            message.Body = "This is a test email message sent by an application. ";

            // Include some non-ASCII characters in body and subject.
            message.BodyEncoding    = System.Text.Encoding.UTF8;
            message.Subject         = $"test message {DateTime.UtcNow.ToLongTimeString()}";
            message.SubjectEncoding = System.Text.Encoding.UTF8;

            // Set the method that is called back when the send operation ends.
            client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);

            // The userState can be any object that allows your callback
            // method to identify this send operation.
            // For this example, the userToken is a string constant.
            string userState = "test message1";

            client.SendAsync(message, userState);

            Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
            string answer = Console.ReadLine();

            // If the user canceled the send, and mail hasn't been sent yet,
            // then cancel the pending operation.
            if (answer.StartsWith("c") && mailSent == false)
            {
                client.SendAsyncCancel();
            }

            // Clean up.
            message.Dispose();
            Console.WriteLine("Goodbye.");
        }
Beispiel #30
0
        public void Email(string body, string title)
        {
            string           addresses     = ConfigurationManager.AppSettings["addresses"];
            ManualResetEvent _ThreadsEvent = new ManualResetEvent(false);

            try
            {
                MailMessage mail = new MailMessage();
                mail.Body       = body;
                mail.IsBodyHtml = true;
                foreach (var address in addresses.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    mail.To.Add(address);
                }
                // mail.To.Add(new MailAddress(email));
                mail.From            = new MailAddress("*****@*****.**", "*****@*****.**", Encoding.UTF8);
                mail.Subject         = title;
                mail.SubjectEncoding = Encoding.UTF8;
                mail.Priority        = MailPriority.Normal;
                SmtpClient smtp = new SmtpClient();
                smtp.Credentials    = new System.Net.NetworkCredential("Webjob", "!1qazxsw2");
                smtp.Host           = "timtam.delek.loc";
                smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
                string userState = "send message";
                mailSent = false;
                smtp.SendAsync(mail, userState);
                _ThreadsEvent.WaitOne(10000);
                if (mailSent == false)
                {
                    smtp.SendAsyncCancel();
                }
                else
                {
                    log.Debug($"Email was send to user {addresses} succesfully");
                }
                // Clean up.
                mail.Dispose();
            }
            catch (SmtpException ex)
            {
                log.Error($"Error message: {ex.StatusCode}");
            }
            catch (Exception ex)
            {
                log.Error($"Error when try send email to user {addresses}, error message: {ex.Message}");
            }
        }