【问题标题】:error in sending mail from separate thread - asp.net/C#从单独的线程发送邮件时出错 - asp.net/C#
【发布时间】:2015-07-28 12:55:06
【问题描述】:

我正在使用从服务器发送邮件的应用程序。因为smtp.send(msg) 与服务器通信需要一些时间。我在单独的线程中制作了发送代码块。之前它工作得很好,但是在添加了计时器控件 timer1(它正在执行一些代码逻辑)之后。由于以下错误,邮件发送被中断:

无法计算表达式,因为代码已经过优化或 本机框架位于调用堆栈的顶部

线程来了..

void sendMail()
{
ThreadStart sendCreateMail = delegate() { Send(subject); };
Thread threadSendCreateMail = new Thread(sendCreateMail);
sendCreateMail.IsBackground = true;
sendCreateMail.Start();
timer1.Enabled = true;
}

net.mail 代码在这里....

protected void Send(string subject)
        {
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient smtp = new SmtpClient("smtp.office365.com");
                var credential = (System.Net.NetworkCredential)smtp.Credentials;
                string Username = credential.UserName;
                string password = credential.Password;
                mail.From = new MailAddress(Username);
                mail.To.Add(toMail);
                mail.Subject = "subject";

                mail.Body = "msg body";
                mail.IsBodyHtml = true;
                smtp.EnableSsl = true;
                smtp.Credentials = new System.Net.NetworkCredential(Username, password);
                smtp.Send(mail);
                }

更新

sendMail 任务适用于其他页面。这是一个弹出窗口,因此我已经告诉过的 timer1 块正在执行弹出关闭功能。它正在停止线程的执行。我能理解(比如 response.end,response.redirect 无法猜出到底是什么,它是一个名为telerik radwindow的第三方工具!)。但是如何克服这一点。

【问题讨论】:

  • 你使用的是什么版本的c#?
  • 你可以寻找更好的选择Asynchronous Programming
  • 你是怎么得到这个错误的?这看起来更像是我在尝试检查调试器中的变量时所期望的,而不是正在运行的程序会给出的错误消息。
  • 错误显示在记录器中。应用程序在运行时看起来很正常,但是邮件发送操作没有发生@Chris
  • 奇怪。那么你的日志记录有问题。我怀疑它由于某些更正常的原因而失败(例如,无法连接到 smtp 服务器或其他原因),但您的日志记录由于某种原因未能真正正确记录这一点。我的方法是先修复日志记录,然后从中找出真正的失败原因并从那里开始工作。

标签: c# asp.net multithreading email system.net.mail


【解决方案1】:

这是我在我的应用程序中使用的

SmtpClient client = new SmtpClient();
client.Port = your port;
client.Host = your host;
client.EnableSsl = true;
client.Timeout = 15000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(your username, your passowrd);
MailMessage mm = new MailMessage(your username, recepient[0], title, message);
for (int a = 1; a < recepient.Count; a++)
    mm.To.Add(recepient[a]);
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client.SendCompleted += (s, e) =>
{
    client.Dispose();
    mm.Dispose();
};
client.SendAsync(mm, null);

【讨论】:

  • 你能告诉我,它与我编写的代码有何不同...... sendAsync 和 dispose 有意义吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-30
  • 2015-07-06
  • 2011-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-30
相关资源
最近更新 更多