通过MailMessage使用和处置附件

问题描述 投票:1回答:1

我有此代码:

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);
    }; 
}

在我的情况下,文件附件为可选。当我在using上使用attachment时,smtp.Send()引发:

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

我的问题是如何正确处理?如果我未在附件上明确使用MailMessageDispose是否也会处置内部附件?

c# email smtp attachment
1个回答
2
投票

[请查看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();
            }
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.