2016-07-15 68 views
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"); 
     } 

    } 
+0

什麼是「smtp.SendMailAsync」的返回類型,由於您沒有正確處理Synchronization上下文,所以程序由於死鎖而掛起。你在用'Task '做什麼,並檢查SendMail函數中的阻塞點 –

+0

如果你使用'Task.WaitAll'來返回'公共異步任務索引',將其替換爲'Task.WhenAll'或'await',以避免阻塞同步上下文。最好是'await',但那需要整個調用鏈才能'異步' –

+0

首先嚐試在沒有附件的情況下重現此問題。 –

回答

2

我以前遇到過這個問題。 Attachments正被保留並需要處理,然後才能刪除它們。沒有對.Dispose的調用,文件被鎖定。試試這個:

[ 
    HttpPost, 
    ValidateAntiForgeryToken 
] 
public async Task<ActionResult> Index(EmailFormModel model, 
             IEnumerable<HttpPostedFileBase> files) 
{ 
    try 
    { 
     if (ModelState.IsValid) 
     { 
      string EncodedResponse = Request.Form["g-Recaptcha-Response"]; 
      bool IsCaptchaValid = ReCaptcha.Validate(EncodedResponse) == "True"; 
      if (IsCaptchaValid) 
      { 
       var paths = GetUploadPaths(files);  
       using (var message = ConstructMailMessage(model)) 
       { 
        AppendAttachments(paths, message.Attachments); 

        using (var smtp = new SmtpClient()) 
        { 
         var credential = new NetworkCredential 
         { 
          UserName = "...", // replace with valid value 
          Password = "..." // 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) => 
         { 
          // Ensure disposed first. 
          foreach (var a in message.Attachments) a.Dispose(); 

          foreach (var path in paths) 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"); 
    } 
} 

我試着在分離一些核心邏輯方面略有不同的方法。例如,現在有一個幫助器方法用於獲取上傳文件路徑GetUploadPaths,另一個用於通過AppendAttachments將附件添加到.Attachments實例。此外,現在有一個ConstructMailMessage函數,它也可以。

public List<string> GetUploadPaths(IEnumerable<HttpPostedFileBase> files) 
{ 
    var paths = new List<string>(); 
    foreach (var file in files) 
    { 
     if (file.ContentLength > 0) 
     { 
      var fileName = Path.GetFileName(file.FileName); 
      var path = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/uploads"), fileName); 
      file.SaveAs(path); 
      paths.Add(path); 
     } 
    } 

    return paths; 
} 

public MailMessage ConstructMailMessage(EmailFormModel model) 
{ 
    var message = new MailMessage(); 
    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; 

    return message; 
} 

public void AppendAttachments(List<string> paths, AttachmentCollection attachments) 
{ 
    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; 
     attachments.Add(new Attachment(memoryStream, fileName)); 
    } 
} 
相關問題