2016-07-15 25 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'です。プログラムは同期化コンテキストを正しく処理していないため、デッドロックが発生してハングしています。あなたは 'Task 'で何をやっているのですか?SendMail関数内のブロッキングポイントを確認してください。 –

+0

'public async Task Index'を返すために' Task.WaitAll'を使用している場合は、 'Task.WhenAll'または' await'を使用して、同期コンテキストをブロックしないようにします。好ましくは 'await'ですが、呼び出しチェーン全体が' async'になる必要があります –

+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と、添付ファイルを追加するためのメソッドである.AttachmentsAppendAttachments経由で取得する方法があります。さらに、それも同様に機能する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)); 
    } 
} 
関連する問題