這是怎麼了,當我需要發送電子郵件給我的錯誤。但自從給我的錯誤是這樣的:發送郵件與SMTP SendAsync
An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>. This exception may also indicate an attempt to call an "async void" method, which is generally unsupported within ASP.NET request processing. Instead, the asynchronous method should return a Task, and the caller should await it.
我已經積累了自MVC,並已使用類來跟蹤頁面的區域。我已經使用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);
}
}
我試着這樣做:
public static async NewPassword(string mail, string name, string password)
{
....
using (var smtpClient = new SmtpClient())
{
await smtp.SendAsync(oMailMessage, null);
}
我已經在這裏看到:https://stackoverflow.com/a/35212320/7391454
據我所知,異步方法需要返回類型 - 無論是否爲空。 – Takarii