我正在一个从服务器发送邮件的应用程序中工作。因为smtp.send(msg)
需要一些时间与服务器通信。我已经在单独的线程中发送了代码块。之前它工作正常,但是在添加了计时器控件 timer1 之后(正在做一些代码逻辑)。由于以下错误,邮件发送被中断:
无法评估表达式,因为代码已优化或a 本机框架位于调用堆栈顶部
线程来到这里..
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
的第三方工具!)。但是如何克服这一点。
答案 0 :(得分:0)
这是我在我的应用程序中使用的
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);