Emailing - Attaching Azure Blobs

May 12, 2020
azure

Sending emails with attachments from Azure blob files. So easy.

This is a quick and easy post on how to attach files to an email when teh file is in Azure.

Previously, I had been downloading the file to a temp directory, attching to the message, sending the message and deleting the file. A lot of work. I know. But, I had the code, it worked and I kept copy & pasting from other places I was using it - that's one of the things that kill us as devs - and why I hate it when people say "don;t micro optimize" pr optimize prematurely, as if it's alin to premature ejaculation, which you defintely do not want to do...

So, we were saying..

We get stuck doing somehting a certain way and just because it's not a oain point, doesn;t mean that optimizing it, or doing it a better way, or asking if there's a better way is premature. the SO folks love to shove that particular flavor of shit doesn everyone's throat that asks "Should I do X or Z?" Myself included. Anyway, that's a rant for a different post.

As I started pushing some stuff to Azure's Linux service, that way of attaching files failed me. I am not 100% certain, but I think it has to do with permissions for writing files on the 'nix box. Those 'nix boxes are sooo complicated. Instead of trying to figure out why, I found a better, faster and definitly more efficient method  - memory streams, from Azure to email and bye.

 

Here's the code:

var stream = new MemoryStream(); //got a stream
CloudBlobContainer container = BlobClient.GetContainerReference(containerName);
CloudBlockBlob blockBlob = container.GetBlockBlobReference(completeName);
await blockBlob.DownloadToStreamAsync(stream); //shove file into stream
stream.Seek(0, SeekOrigin.Begin); //reset stream - this one will bite you!
Mailman.Attachments.Add(new Attachment(stream, fileMa,e));

 

 

So, I didn't declare the variables, since I just copied the relevent code from source, but I'm sure you can see what's going on. Mailman, incidentally, is just an email service I put together to make senidng emails easier. But the attachment piece is the same if you were using MailMessage.

And that's it. No temp directory, no downloads and uploads, etc. TBH, I am not 100% certain that this is better than downloading and uploading, but I have to imagineit is.