C# 通过SmtpClient(ASP.NET MVC)发送邮件后删除附件

C# 通过SmtpClient(ASP.NET MVC)发送邮件后删除附件,c#,asp.net-mvc,asp.net-mvc-5,delete-file,C#,Asp.net Mvc,Asp.net Mvc 5,Delete File,我在一个网站上工作,它可以发送一个带有多个附加/上传文件的表单,附加的文件存储在App_Data/uploads文件夹中。App_Data/uploads文件夹中的文件是否有可能在发送到电子邮件后立即被删除?谢谢你的帮助。这是我的控制器: [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Index(EmailFormModel model, IEnumerable<HttpPostedF

我在一个网站上工作,它可以发送一个带有多个附加/上传文件的表单,附加的文件存储在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);

    }
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务索引(EmailFormModel模型、IEnumerable文件)
{
if(ModelState.IsValid)
{ 
列表路径=新列表();
foreach(文件中的var文件)
{
如果(file.ContentLength>0)
{
var fileName=Path.GetFileName(file.fileName);
var path=path.Combine(Server.MapPath(“~/App\u Data/uploads”),文件名);
file.SaveAs(路径);
路径。添加(路径);
}
}
var message=new MailMessage();
foreach(路径中的变量路径)
{
var fileInfo=新文件信息(路径);
var memoryStream=新的memoryStream();
使用(var stream=fileInfo.OpenRead())
{
stream.CopyTo(memoryStream);
}
memoryStream.Position=0;
字符串文件名=fileInfo.Name;
添加(新附件(memoryStream,fileName));
}
//这里是业务逻辑的其余部分
字符串EncodedResponse=Request.Form[“g-Recaptcha-Response”];
bool IsCaptchaValid=(ReCaptcha.Validate(EncodedResponse)=“真”?真:假);
if(IsCaptchaValid)
{
var body=“电子邮件发件人:{0}({1})

主题:{2}

消息:

{3}

软件描述:

{4}

”; message.To.Add(新邮箱地址(“***@gmail.com”); message.From=新邮件地址(“***@ymailcom”); message.Subject=“您的电子邮件主题”; message.Body=string.Format(Body,model.FromName,model.FromEmail,model.FromSubject,model.message,model.Desc); message.IsBodyHtml=true; 使用(var smtp=new SmtpClient()) { var-credential=新网络凭据 { UserName=“***@gmail.com”, Password=“***” }; smtp.Credentials=凭证; smtp.Host=“smtp.gmail.com”; smtp.Port=587; smtp.EnableSsl=true; 等待smtp.SendMailAsync(消息); ViewBag.Message=“您的邮件已发送!”; ModelState.Clear(); 返回视图(“索引”); } }否则 { TempData[“recaptcha”]=“请确认您不是机器人!”; } }返回视图(模型); }
您可以使用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");
}

由于文件原因,出现“存在在给定上下文中无效的方法”错误。删除Sir。谢谢你的帮助。:)System.Web.Mvc.Controller.File(byte[],string)”是一个“方法”,在给定的上下文中无效“@KenHemmo,好的,System.Web.Mvc.Controller也使用了该名称,所以您只需在使用File方法之前使用
System.IO
名称空间,我将更新我的答案。我建议您将问题的标题编辑为”请在通过SmtpClient(ASP.NET MVC)发送邮件后删除附件”,以帮助其他人在遇到相同问题时更好地找到您的问题。