简体   繁体   English

使用System.Net.Mail发送带有附件的电子邮件

[英]Send email with attchement using System.Net.Mail

I am using System.Net.Mail to send emails through my application. 我正在使用System.Net.Mail通过我的应用程序发送电子邮件。 I was trying to send emails with the attachments with following code. 我试图使用以下代码发送附件的电子邮件。

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

When I send the emails with the attachments it throw an exceptions as follows. 当我发送带有附件的电子邮件时,它会抛出如下例外情况。

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)

The ending curly brace of your using statement closes the file stream: using语句的结束花括号将关闭文件流:

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

However, the stream is read at the time of the stmpClient.Send(mailMessage) , where it is not open anymore. 但是,在stmpClient.Send(mailMessage)时读取流,此时它不再打开。

The simplest solution is to provide just the file name instead of a stream: 最简单的解决方案是仅提供文件名而不是流:

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

With this solution, the .NET library will have to worry about opening, reading and closing the file. 使用此解决方案,.NET库将不得不担心打开,读取和关闭文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM