【问题标题】:Delete attached files after sending mail via SmtpClient ( ASP.NET MVC)通过 SmtpClient ( ASP.NET MVC) 发送邮件后删除附件
【发布时间】:2016-06-15 16:32:41
【问题描述】:

我正在开发一个可以发送带有多个附加/上传文件的表单的网站,附加的文件存储在 App_Data/uploads 文件夹中。 App_Data/uploads 文件夹中的文件是否有可能在通过电子邮件发送后立即被删除?谢谢您的帮助。这是我的控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(EmailFormModel model, IEnumerable<HttpPostedFileBase> files)
{
    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(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>Message:</b></p><p>{3}</p><p><b>Software Description:</b></p><p>{4}</p>";
                message.To.Add(new MailAddress("***@gmail.com"));   
                message.From = new MailAddress("***@ymailcom"); 
                message.Subject = "Your email subject";
                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 = "***@gmail.com",  
                        Password = "***" 
                    };
                    smtp.Credentials = credential;
                    smtp.Host = "smtp.gmail.com";
                    smtp.Port = 587;
                    smtp.EnableSsl = true;
                    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);

    }

【问题讨论】:

  • 我建议将您的问题标题编辑为“通过 SmtpClient (ASP.NET MVC) 发送邮件后删除附件”,以帮助其他人在遇到相同问题时更好地找到您的问题,问候。

标签: c# asp.net-mvc asp.net-mvc-5 delete-file


【解决方案1】:

发送后可以使用SmtpClient的SendCompleted事件删除文件:

smtp.SendCompleted += (s, e) => {
                       //delete attached files
                       foreach (var path in paths)
                          System.IO.File.Delete(path);
                    };

所以发送部分应该是这样的:

using (var smtp = new SmtpClient())
{
       var credential = new NetworkCredential
       {
              UserName = "***@gmail.com",  
              Password = "***" 
       };
       smtp.Credentials = credential;
       smtp.Host = "smtp.gmail.com";
       smtp.Port = 587;
       smtp.EnableSsl = true;
       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");
}

【讨论】:

  • 由于 File.Delete Sir 存在“是一种在给定上下文中无效的方法”错误。谢谢您的帮助。 :)
  • 'System.Web.Mvc.Controller.File(byte[], string)' 是一个'方法',在给定的上下文中是无效的"
  • @KenHemmo,Ok,System.Web.Mvc.Controller 也使用了该名称,因此您只需在 File 方法之前使用 System.IO 命名空间,我会更新我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多