【问题标题】:using and disposing Attachment with MailMessage使用和处理带有 MailMessage 的附件
【发布时间】:2019-11-01 07:33:30
【问题描述】:

我有这个代码:

using (var msg = new System.Net.Mail.MailMessage())
{
    msg.Subject = subject;
    msg.From = new System.Net.Mail.MailAddress(fromEmail);
    msg.To = new System.Net.Mail.MailAddress(toEmail);        
    msg.Body = body;

    var attachment = new System.Net.Mail.Attachment(file);
    msg.Attachments.Add(attachment);

    //using (var attachment = new System.Net.Mail.Attachment(file))
    //    msg.Attachments.Add(attachment);

    using (var smtp = new System.Net.Mail.SmtpClient("smtp", 587))
    {
        smtp.Send(msg);
    }; 
}

在我的情况下,文件附件是可选
当我在attachment 上使用using 时,smtp.Send() 会抛出:

内部异常 1:ObjectDisposedException:无法访问已关闭的 文件

我的问题是如何正确处理这个问题? 如果我没有在附件上明确使用DisposeMailMessage 是否也会处理内部附件?

【问题讨论】:

    标签: c# email smtp attachment


    【解决方案1】:

    请查看MailMessage的.net源代码

    如果有附件,将被丢弃。

    protected virtual void Dispose(bool disposing)
        {
            if (disposing && !disposed)
            {
                disposed = true;
    
                if(views != null){
                    views.Dispose();
                }
                if(attachments != null){
                    attachments.Dispose();
                }
                if(bodyView != null){
                    bodyView.Dispose();
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多