Jas*_*per 2 c# asp.net email asynchronous
这就是当我需要发送电子邮件时给我错误的方式。但是因为给我的错误是这样的:
此时无法启动异步操作。异步操作只能在异步处理程序或模块内或在页面生命周期中的某些事件期间启动。如果在执行 Page 时发生此异常,请确保将 Page 标记为 <%@ Page Async="true" %>。此异常还可能表示尝试调用“async void”方法,该方法在 ASP.NET 请求处理中通常不受支持。相反,异步方法应该返回一个任务,调用者应该等待它。
我从 MVC 开始积累,并使用类来跟踪页面的 ie 区域。我使用 SendAsync 的原因恰恰是发送电子邮件等的速度要快一些。
此错误仅在我尝试向用户发送电子邮件时发生。
public static void NewPassword(string mail, string name, string password)
{
MailDefinition oMailDefinition = new MailDefinition();
oMailDefinition.BodyFileName = "~/MailList/emailskabelon/NewPassword.html";
oMailDefinition.From = FromMail;
Dictionary<string, string> oReplacements = new Dictionary<string, string>();
oReplacements.Add("<<navn>>", name);
oReplacements.Add("<<password>>", password);
System.Net.Mail.MailMessage oMailMessage = oMailDefinition.CreateMailMessage(mail, oReplacements, new LiteralControl());
oMailMessage.Subject = NewpasswordTitle + WebsiteName;
oMailMessage.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient(AzureApi);
System.Net.NetworkCredential netcred = new System.Net.NetworkCredential(AzureName, AzurePassword);
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = netcred;
smtp.Port = Convert.ToInt32("25");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
using (var smtpClient = new SmtpClient())
{
smtp.SendAsync(oMailMessage, null);
}
}
Run Code Online (Sandbox Code Playgroud)
我试过这样做:
public static async NewPassword(string mail, string name, string password)
{
....
using (var smtpClient = new SmtpClient())
{
await smtp.SendAsync(oMailMessage, null);
}
Run Code Online (Sandbox Code Playgroud)
将您的方法更改为:
public async Task SendEmail(string toEmailAddress, string emailSubject, string emailMessage)
{
var message = new MailMessage();
message.To.Add(toEmailAddress);
message.Subject = emailSubject;
message.Body = emailMessage;
using (var smtpClient = new SmtpClient())
{
await smtpClient.SendMailAsync(message);
}
}
Run Code Online (Sandbox Code Playgroud)
并称之为:
var task = SendEmail(toEmailAddress, emailSubject, emailMessage);
var result = task.WaitAndUnwrapException();
Run Code Online (Sandbox Code Playgroud)
看看这里在 C# 中异步发送电子邮件? 在这里如何从 C# 中的同步方法调用异步方法?