9

我正在使用 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)
4

1 回答 1

15

语句的结尾大括号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 库将不得不担心打开、读取和关闭文件。

于 2012-04-19T06:02:32.157 回答