c# - 使用和处理带有 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);
};
}
就我而言,文件附件是可选的。
当我使用using
onattachment
时,smtp.Send()
抛出:
内部异常 1:ObjectDisposedException:无法访问已关闭的文件
我的问题是如何正确处理这个问题?MailMessage
如果我没有在附件上明确使用,是否也会处理内部附件Dispose
?
解决方案
如果有附件,将被丢弃。
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();
}
}
}
推荐阅读
- javascript - querySelector 不适用于 puppeteer 中的子元素
- java - 如何在使用 mvn clean install 时避免在不使用 maven 中的 skipTests 的情况下运行测试用例
- laravel - Illuminate\Broadcasting\BroadcastException: auth_key 应该是一个有效的应用程序密钥 laravel 5.8
- javascript - 困扰我一整天的问题。标签中的“type”属性和“as”属性有什么区别?
- python - AES/PKCS5/SHSA256
- javascript - 如何在文本更改上应用新的 CSS
- java - Testcontainers 快速入门示例不起作用?
- swift - tableviewcell 在滚动时更改图像
- python - Python检查是否有多个程序正在运行,然后将一个值写入文件
- visual-studio - Visual Studio 2019 16.7.5 崩溃 - Nuget