1
我一直在一個網站,您可以直接發送查詢郵件到特定的電子郵件。郵件發送,但從不返回
起初我以爲郵件沒有發送,因爲我點擊發送按鈕後,網站只是繼續加載。但是當我查看我的電子郵件時,我驚訝於我發送的郵件在那裏。但是當我查看我的網站時(我有查詢表單),它仍然在加載。
該ViewBag,假設說「您的消息已發送!」即使我已經收到郵件,仍然不顯示。好像
await smtp.SendMailAsync(message);
不返回。我是新來的這種事情。我希望有人能幫助我。先謝謝你。這裏是我的控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(EmailFormModel model, IEnumerable<HttpPostedFileBase> files)
{
try
{
if (ModelState.IsValid)
{
List<string> paths = new List<string>();
foreach (var file in files)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
paths.Add(path);
}
}
var message = new MailMessage();
foreach (var path in paths)
{
var fileInfo = new FileInfo(path);
var memoryStream = new MemoryStream();
using (var stream = fileInfo.OpenRead())
{
stream.CopyTo(memoryStream);
}
memoryStream.Position = 0;
string fileName = fileInfo.Name;
message.Attachments.Add(new Attachment(memoryStream, fileName));
}
//Rest of business logic here
string EncodedResponse = Request.Form["g-Recaptcha-Response"];
bool IsCaptchaValid = (ReCaptcha.Validate(EncodedResponse) == "True" ? true : false);
if (IsCaptchaValid)
{
var body = "<p><b>Email From:</b> {0} ({1})</p><p><b>Subject:</b> {2} </p><p><b>Software Description:</b></p><p>{4}</p><p><b>Message:</b></p><p>{3}</p>";
message.To.Add(new MailAddress("[email protected]")); // replace with valid value
message.From = new MailAddress("[email protected]"); // replace with valid value
message.Subject = "(Inquire for SELLING)";
message.Body = string.Format(body, model.FromName, model.FromEmail, model.FromSubject, model.Message, model.Desc);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "[email protected]", // replace with valid value
Password = "0000" // replace with valid value
};
smtp.Credentials = credential;
smtp.Host = "relay-hosting.secureserver.net";
smtp.Port = 25;
smtp.Timeout = 1000;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.SendCompleted += (s, e) =>
{
//delete attached files
foreach (var path in paths)
System.IO.File.Delete(path);
};
await smtp.SendMailAsync(message);
ViewBag.Message = "Your message has been sent!";
ModelState.Clear();
return View("Index");
}
}
else
{
TempData["recaptcha"] = "Please verify that you are not a robot!";
}
} return View(model);
}
catch (Exception ex)
{
return View("Error");
}
}
什麼是「smtp.SendMailAsync」的返回類型,由於您沒有正確處理Synchronization上下文,所以程序由於死鎖而掛起。你在用'Task'做什麼,並檢查SendMail函數中的阻塞點 –
如果你使用'Task.WaitAll'來返回'公共異步任務索引',將其替換爲'Task.WhenAll'或'await',以避免阻塞同步上下文。最好是'await',但那需要整個調用鏈才能'異步' –
首先嚐試在沒有附件的情況下重現此問題。 –