Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple memory streams for e-mail attachments

Tags:

c#

.net

smtp

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?

like image 610
Daniel Minnaar Avatar asked Sep 05 '25 19:09

Daniel Minnaar


2 Answers

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();
}
like image 128
Rob S. Avatar answered Sep 08 '25 08:09

Rob S.


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.

like image 44
Eric Lemes Avatar answered Sep 08 '25 08:09

Eric Lemes