在asp.net C#中发送电子邮件后如何删除附件?

时间:2015-10-29 13:25:28

标签: c# asp.net email email-attachments

在我的网站中,用户从他的系统上传一些文件并发送电子邮件。

try
{
  if(Request.Files!=null)
  {
     //save the file to some temp location 
     //Attach the file to email & send
  }
}
catch(Exception ex)
{
  //log exception
}
finally
{
    //delete the file from temp location
    System.IO.File.Delete(attachmentLocation);
}

但是如果电子邮件发送失败,那么我可以删除该文件但是如果成功发送电子邮件,那么我会收到异常

  

无法删除文件test.pdf,因为其他进程使用

是否可以在不保存的情况下附加文件?

如果没有,那么我如何在发送电子邮件后删除文件?

供参考: - 这是一个AJAX调用。

2 个答案:

答案 0 :(得分:1)

我认为这两个解决方案中的一个可以使用第一个链接,我认为是您问题的解决方案

“要解决此问题,基本上您需要在Dispose ( )对象上调用MailMessage(然后在Dispose ( )对象上调用Attachment,从而释放锁定文件,并允许您删除它。)

有两种明显的方法可以做到这一点:

1)通过MailMessage参数将SendAsync ()对象传递给UserToken。然后,在SendCompletedCallback方法中,转换为MailMessage e.UserState类型,并在其上调用Dispose ( )

http://www.dreamincode.net/forums/topic/325303-c%23how-to-delete-attach-file-after-send-mail/

http://www.codeproject.com/Questions/360228/how-to-delete-attachment-file-after-it-is-send-as

答案 1 :(得分:1)

您可以使用保存文件

来实现它
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))    
using (var mailClient = new SmtpClient("localhost", 25))
using (var message = new MailMessage("me@example.com", "you@example.com", "Just testing", "See attachment..."))
{
    writer.Flush();
    stream.Position = 0;     

    message.Attachments.Add(new Attachment(stream, "filename.csv", "text/csv"));

    mailClient.Send(message);
}

现在你只需要从文件中获取memorystrem

var postedFile = httpRequest.Files[0];
using (var binaryReader = new BinaryReader(postedFile.InputStream))
{
   var zz = new MemoryStream(binaryReader.ReadBytes(postedFile.ContentLength));
}