邮件发送但永不返回

时间:2016-07-15 06:36:06

标签: c# asp.net-mvc asynchronous smtp async-await

我一直在网站上工作,您可以直接将查询邮件发送到特定的电子邮件。

起初我认为邮件没有发送,因为我点击发送按钮后网站只是继续加载。但是,当我检查我的电子邮件时,我很惊讶我发送的邮件就在那里。但是,当我检查我的网站(我有查询表格)时,它仍在加载。

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@mydomain.com"));  // replace with valid value 
                message.From = new MailAddress("email@randomdomain.com");  // 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@mydomain.com",  // 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");
        }

    }

1 个答案:

答案 0 :(得分:2)

之前我遇到过同样的问题。在您删除它们之前,.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

我尝试了一种稍微不同的方法来分离一些核心逻辑。例如,现在有一种帮助方法可以获取上传文件路径.Attachments,另一种方法可以通过AppendAttachments附加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@mydomain.com")); // replace with valid value message.From = new MailAddress("email@randomdomain.com"); // 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)); } } 函数也能正常工作。

$temp = Array
(
[@url] => url
[@type] => image/jpeg
[@expression] => full
[@width] => 644
[@height] => 429
)