2012-04-19 11 views
6

私はSystem.Net.Mailを使用して自分のアプリケーションから電子メールを送信しています。私は次のコードで添付ファイル付きの電子メールを送信しようとしていました。System.Net.Mailを使用してattchementで電子メールを送信

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

メールを添付ファイルとともに送信すると、次のように例外がスローされます。

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

ただし、ストリームは、それはもう開いていないstmpClient.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) 

答えて

11

あなたusing文の終わり中括弧は、ファイルストリームを閉じます。

最も簡単な解決策ではなく、ストリームのファイル名のみを提供することである。

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ライブラリが開き、読み取りとファイルを閉じるを心配する必要があります。

+0

完了...ファイルストリームを削除しました – udaya726

関連する問題