I'm trying to construct an EmailMessage using multiple in-memory streams. However, when I send the e-mail, I get the following error:
"One of the streams has already been used and can't be reset to the origin"
From what I can gather, I think the problem may be that the message is losing context of the memory stream when I try to do the following:
foreach (var att in attachments)
{
doc = fetchDocumentByteArray();
using (MemoryStream ms = new MemoryStream(doc))
{
mailToSend.AddAttachment(new Attachment(ms, att.Filename));
}
}
mailToSend.Send();
I've also tried setting the ms.Position = 0
before the AddAttachment(), but that doesn't work.
After looking around a bit for a scenario like mine, I came across a suggestion to use a List<MemoryStream>
- but I'm not sure how I'd implement this or if it's even the correct approach?
The accepted answer did not work for me because you need to keep track of multiple MemoryStreams and dispose of each individually. I took the same approach but implemented it slightly differently adding each MemoryStream to a list and then calling Dispose() on each instance after the email is sent.
var msList = new List<MemoryStream>();
foreach (var attachment in message.Attachments)
{
var ms = new MemoryStream(attachment.Bytes);
msList.Add(ms);
var mailAttachment = new Attachment(ms, attachment.FileName);
mailMessage.Attachments.Add(mailAttachment);
}
smtp.Send(mailMessage);
foreach (var ms in msList)
{
ms.Dispose();
}
When you use "using" keywork, internally, Dispose method is invoked. It will make the MemoryStreams be deallocated.
Remove the using in your inner loop and create a try/finally clause to dispose the memory streams after the e-mail is sent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With