gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:36:37 25 4
gpt4 key购买 nike

我在一个从服务器发送邮件的应用程序中工作。因为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com