【问题标题】:Send email with attchement using System.Net.Mail thows exception: Cannot access a closed file使用 System.Net.Mail 发送带附件的电子邮件会引发异常:无法访问已关闭的文件
【发布时间】:2012-04-30 15:08:30
【问题描述】:

我正在使用 System.Net.Mail 通过我的应用程序发送电子邮件。我正在尝试使用以下代码发送带有附件的电子邮件。

    Collection<string> MailAttachments = new Collection<string>();
    MailAttachments.Add("C:\\Sample.JPG");
    mailMessage = new MailMessage();
    foreach (string filePath in emailNotificationData.MailAttachments)
    {
      FileStream fileStream = File.OpenWrite(filePath);
      using (fileStream)
       {
        Attachment attachment = new Attachment(fileStream, filePath);
        mailMessage.Attachments.Add(attachment);
       }
    }
     SmtpClient smtpClient = new SmtpClient();
     smtpClient.Host = SmtpHost;
     smtpClient.Send(mailMessage);

当我发送带有附件的电子邮件时,它会抛出如下异常。

Cannot access a closed file.
at System.IO.__Error.FileNotOpen()
at System.IO.FileStream.Read(Byte[] array, Int32 offset, Int32 count)
at System.Net.Mime.MimePart.Send(BaseWriter writer)
at System.Net.Mime.MimeMultiPart.Send(BaseWriter writer)
at System.Net.Mail.Message.Send(BaseWriter writer, Boolean sendEnvelope)
at System.Net.Mail.MailMessage.Send(BaseWriter writer, Boolean sendEnvelope)
at System.Net.Mail.SmtpClient.Send(MailMessage message)

【问题讨论】:

    标签: c# c#-2.0 smtpclient


    【解决方案1】:

    using 语句的结尾大括号关闭文件流:

    using (fileStream)
    {
        Attachment attachment = new Attachment(fileStream, filePath);
        mailMessage.Attachments.Add(attachment);
    }  // <-- file stream is closed here
    

    但是,流是在stmpClient.Send(mailMessage) 时读取的,它不再打开。

    最简单的解决方案是只提供文件名而不是流:

    Collection<string> MailAttachments = new Collection<string>();
    MailAttachments.Add("C:\\Sample.JPG");
    
    mailMessage = new MailMessage();
    foreach (string filePath in emailNotificationData.MailAttachments)
    {
        Attachment attachment = new Attachment(filePath);
        mailMessage.Attachments.Add(attachment);
    }
    SmtpClient smtpClient = new SmtpClient();
    smtpClient.Host = SmtpHost;
    smtpClient.Send(mailMessage);
    

    使用此解决方案,.NET 库将不得不担心打开、读取和关闭文件。

    【讨论】:

    • 完成...我已删除文件流
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 2019-05-22
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多