簡體   English   中英

通過SmtpClient(ASP.NET MVC)發送郵件后,刪除附件

[英]Delete attached files after sending mail via SmtpClient ( ASP.NET MVC)

我正在一個網站上工作,該網站可以發送包含多個附件/上傳文件的表單,所附加的文件存儲在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的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");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM