c# - 如何在 MVC 应用程序中使用 SMTP 客户端发送电子邮件后删除服务器上保存的文件

标签 c# asp.net asp.net-mvc iis smtpclient

我有一个关于 M.V.C 4 C# 互联网应用程序的项目,我遵循了一些指南,使用 ajax 功能将 Google 可视化柱形图保存到我的驱动器中的图像中。此外,我正在使用 razor P.D.F nugget 包制作 P.D.F 格式的报告。路径是:“C\temp\”,这两个文件都在那里。我需要将这两个文件附加到电子邮件中并发送它们,然后删除创建的文件。

我使用ajax调用发送电子邮件功能:

$('#btnSend').on('click', function () {
            if (from) {
                fromDate = from.toJSON();
            }

            if (to) {
                toDate = to.toJSON();
            }
            // from and to are dates taken from two datepickers

            // saves the pdf to the server
            if (from && to) {
                $.ajax({
                    url: "/Home/SavePdf/",
                    data: { fromDate: fromDate, toDate: toDate },
                    type: 'GET',
                    async: false,
                    datatype: 'json',
                    success: function (data) {
                        alert('got here with data');
                    },
                    error: function () { alert('something bad happened'); }
                });
            }


            // saves the column chart to the server from canvas item with id reports

            var imgData = getImgData(document.getElementById("reports"));
            var imageData = imgData.replace('data:image/png;base64,', '');

            $.ajax({
                url: "/Home/SaveImage/",
                type: 'POST',
                data: '{ "imageData" : "' + imageData + '" }',
                datatype: 'json',
                async: false,
                contentType: 'application/json; charset=utf-8',
                success: function () {
                    alert('Image saved successfully !');
                },
                error: function () {
                    alert('something bad happened');
                }
            });

            $.ajax({
                type: "POST",
                url: "/Home/SendMail/",
                async: false,
                success: function() {
                    alert('Message sent successfully');
                }
            });
        });

这是我在后面的代码中的函数

public void SendMail()
        {
            var path = @"C:\temp\";
            string pngFilePath = path + DateTime.Now.ToShortDateString() + ".png";
            string pdfFilePath = path + DateTime.Now.ToShortDateString() + ".pdf";

            MailMessage message = new MailMessage("message sender", "message reciever")
            {
                Subject = "Test",
                Body = @"Test"
            };
            Attachment data = new Attachment(pdfFilePath , 

 MediaTypeNames.Application.Pdf);
        message.Attachments.Add(data);

        Attachment data2 = new Attachment(pngFilePath , GetMimeType(pngFilePath); 
 // GetMimeType function gets the mimeType of the unknown attachment
        message.Attachments.Add(data2);

        SmtpClient client = new SmtpClient();
        client.Host = "smtp.googlemail.com";
        client.Port = 587;
        client.UseDefaultCredentials = true;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.EnableSsl = true;
        client.Credentials = new NetworkCredential("mail sender", "sender password");
        client.Send(message);

        // delete the png after message is sent
        if ((System.IO.File.GetAttributes(pngFilePath ) & FileAttributes.Hidden) == FileAttributes.ReadOnly) 
        {

            System.IO.File.SetAttributes(pngFilePath , FileAttributes.Normal);            

            if (System.IO.File.Exists(pngFilePath ))  
            {     
                System.IO.File.Delete(pngFilePath ); 
            }  
        }

        // delete the pdf after message is sent
        if ((System.IO.File.GetAttributes(pdfFilePath ) & FileAttributes.Hidden) == FileAttributes.ReadOnly)
        {

            System.IO.File.SetAttributes(pdfFilePath , FileAttributes.Normal);

            if (System.IO.File.Exists(pdfFilePath ))
            {
                System.IO.File.Delete(pdfFilePath );
            }
        }
    }

我想删除这些文件,但 IIS 继续使用它们,并且永远无法执行删除操作。有什么方法可以从 iis 中解除这些文件并删除它们吗?

最佳答案

SmtpClient 锁定文件。为每个文件创建一个流并将其用作附件。 像这样的事情:

using(Stream fs1 = File.OpenRead(pdfFilePath))
using(Stream fs2 = File.OpenRead(pngFilePath))
{
   Attachment data = new Attachment(fs1 , GetMimeType(pdfFilePath));
   Attachment data2 = new Attachment(fs2 , GetMimeType(pngFilePath));
   message.Attachments.Add(data);
   message.Attachments.Add(data2);
   ...
   client.Send(message);
}

编辑:我最初的建议是在发送邮件后使用 client.Dispose() ,但似乎不起作用

关于c# - 如何在 MVC 应用程序中使用 SMTP 客户端发送电子邮件后删除服务器上保存的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19840782/

相关文章:

c# - <%# 的新手 - 奇怪的错误

javascript - Ajax 完全没有被调用

asp.net-mvc - 在ASP.NET MVC中,如何更改操作参数并使它正常工作而不更改路由?

c# - 如何使用矩阵旋转矩形并获得修改后的矩形?

c# - asp.net mvc 中的 LINQ + EntityFunctions

c# - 如何删除 Telerik RadTextBox 中显示的先前数据

jquery - 在 MVC 3 中,如果不显眼的验证无效则显示 div,如果有效则隐藏它

javascript - Durandal 路由

c# - 如何将整个数组附加到 C# 中的字符串

c# - (WCF - C#) 返回包含不同自定义类集合的自定义类