Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SendGrid: How to attach a file from Azure blob storage?

I have blobs in Windows Azure blob storage that I'd like to attach to emails sent with SendGrid. I'd like to specify the file name for the attachment (real file names are just mumbo jumbo) which afaik forces me to add the attachment as a stream.

My code looks like this:

var msg = SendGrid.GetInstance();
// Code for adding sender, recipient etc...
var storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["storage"].ConnectionString);
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference(typeName);
var blob = container.GetBlockBlobReference("somefile.png");
var ms = new MemoryStream();
blob.DownloadToStream(ms);
msg.AddAttachment(ms, "originalfilename.png");

The file gets read from the storage to the memory stream and adding the attachment seems to work fine but after receiving the email the attached file is 0 bytes.

Thank you in advance.

like image 757
HSBallina Avatar asked Dec 28 '25 17:12

HSBallina


2 Answers

This has probably already been solved, but you need to make sure that you 'rewind' the stream back to the beginning using Seek. Sample code below.

stream.Seek(0, SeekOrigin.Begin);
sendGrid.AddAttachment(stream, "name");
like image 134
drigofonte Avatar answered Dec 31 '25 11:12

drigofonte


Even though I am not sure how AddAttachment API works, please note that your MemoryStream's position will be set to its length at the end of the download. Hence, you might need to seek it to the beginning before calling AddAttachment.

var ms = new MemoryStream();
blob.DownloadToStream(ms);
ms.Position = 0;
msg.AddAttachment(ms, "originalfilename.png");
like image 23
Serdar Ozler Avatar answered Dec 31 '25 11:12

Serdar Ozler