使用和处理 MailMessage 的附件
using and disposing Attachment with MailMessage
我有这个代码:
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()
抛出:
Inner Exception 1: ObjectDisposedException: Cannot access a closed
file
我的问题是如何正确处理这个问题?
如果我没有在附件上明确使用 Dispose
,MailMessage
是否也会处理内部附件?
请查看 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();
}
}
}
我有这个代码:
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()
抛出:
Inner Exception 1: ObjectDisposedException: Cannot access a closed file
我的问题是如何正确处理这个问题?
如果我没有在附件上明确使用 Dispose
,MailMessage
是否也会处理内部附件?
请查看 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();
}
}
}