c# - 从单独的线程发送邮件时出错 - asp.net/C#

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

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

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

线程 来到这里..

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 block 正在执行弹出窗口关闭功能。它在那里停止线程的执行。我可以理解(比如 response.end,response.redirect 猜不出来到底是什么,它是一个名为 telerik radwindow 的第三方工具!)。但如何克服这一点。

最佳答案

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

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);

关于c# - 从单独的线程发送邮件时出错 - asp.net/C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31676961/

相关文章:

python - 将来在不同的时间启动(非常短的) Action 时如何避免启动数百个线程

c# - 方法重载还是更优雅的东西?

ASP.NET Core 中使用 IActionResult 的 C# 接口(interface)概念说明

c++ - SIGABRT 在线程中访问内存时

asp.net - 如何在谷歌分析中记录每一刻?

javascript - 我无法通过 Jquery 弹出窗口更新数据

C++ 线程安全、基于上下文流的日志记录

c# - Bentley-Ottmann 算法实现

c# - 在 WebSocket4Net 中使用客户端证书

asp.net - Ajax 程序集错误 - 程序集 {0} 不包含名称为 {1} 的 Web 资源