邮件发送但从不返回

本文关键字:返回 | 更新日期: 2023-09-27 17:57:00

我一直在开发一个网站,您可以在其中直接向特定电子邮件发送查询邮件。

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

假设说"您的消息已发送!"的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");
        }
    }

邮件发送但从不返回

我以前遇到过同样的问题。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@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));
    }
}