lee_mcmullen lee_mcmullen - 5 days ago 6
C# Question

AddAttachment from MemoryStream

The SendGrid API docs specify you can add attachments from a Stream. The example it gives uses a

object.

I have some blobs in Azure Storage which I'd like to email as attachments. To achieve this I'm trying to use a
MemoryStream
:

var getBlob = blobContainer.GetBlobReferenceFromServer(fileUploadLink.Name);
if(getBlob != null)
{
// Get file as a stream
MemoryStream memoryStream = new MemoryStream();
getBlob.DownloadToStream(memoryStream);
emailMessage.AddAttachment(memoryStream, fileUploadLink.Name);
}
emailTransport.Deliver(emailMessage);


It sends fine but when the email arrives, the attachment appears to be there but it's actually empty. Looking at the email source, there is no content for the attachment.

Is using a
MemoryStream
a known limitation when using the SendGrid C# API to send attachments? Or should I be approaching this in some other way?

Answer

I ended up with the following which fixed the issue for me:

fileByteArray = new byte[getBlob.Properties.Length];
getBlob.DownloadToByteArray(fileByteArray, 0);
attachmentFileStream = new MemoryStream(fileByteArray);
emailMessage.AddAttachment(attachmentFileStream, fileUploadLink.Name);
Comments