MVCMailer SendAsync和删除附件

时间:2011-08-11 23:49:37

标签: asp.net-mvc mailmessage sendasync mvcmailer

我无法在异步发送电子邮件后让MVCMailer删除附件。

我无法弄清楚如何处理邮件以释放附加到邮件附件的进程。

按照说明here ....

    private IUserMailer userMailer = new UserMailer();

    public IUserMailer UserMailer
    {
        get { return this.userMailer; }
        set { this.userMailer = value; }
    }


      using (SmtpClientWrapper client = new SmtpClientWrapper())
        {
            client.SendCompleted += (sender, e) =>
            {
                if (e.Error != null || e.Cancelled)
                {
                    // Handle Error
                }

                //Use e.UserState

                //?? How can I use the userstate?? There are no
                // instructions??

                // Delete the saved attachments now. 
                // This will not work since the mailmessage process 
                // is still attached.
                Parallel.ForEach(imageList, image =>
                {

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

                });

            };

            // SendAsync() extension method: using Mvc.Mailer
            // farm is my model imageList is a list of file locations for the 
            // uploaded attachments
          UserMailer.Submission(farm, imageList).SendAsync("user state object",
                                                            client);
        }

2 个答案:

答案 0 :(得分:1)

您可以在使用语句中运行中断SmtpClientWrapper,并在清理附件之前手动调用dispose。

答案 1 :(得分:1)

显示我的成功解决方案:

        MailMessage message = UserMailer.Submission(farm, imageList);

        SmtpClientWrapper client = new SmtpClientWrapper();

        client.SendCompleted += (sender, e) =>
        {
            if (e.Error != null || e.Cancelled)
            {
                // Handle Error
            }

            if (message != null)
            {
                message.Attachments.Dispose();
                message.Dispose();

                // Delete the saved attachments now
                Parallel.ForEach(imageList, image =>
                {

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

                });

            }

            client.Dispose();

        };

        // SendAsync() extension method: using Mvc.Mailer
        message.SendAsync("farm message", client);