2

I have an Azure Timer Trigger function, which generates an excel file, and I need to send it via an email, as an attachment. I have done the following successfully -

  1. Created the file and uploaded it into an azure blob
  2. Sent email without attachment (Using SmtpClient and MailMessage)

How can I fetch the file from Azure Blob and send it as an attachment?

P.S. I was able to send it as an attachment, when I stored the file in Azure's local storage of the function. However, I want to move the storage of the file to Azure Blob

Raj
  • 417
  • 1
  • 3
  • 17
  • If I understand correctly, you're creating the file locally in your Function and then uploading that file to blob storage. Correct? If that's the case, then why can't you simply attach that local file to the email? – Gaurav Mantri Dec 28 '17 at 06:55
  • @GauravMantri No, I'm not storing the file locally, before uploading to blob. I'm directly uploading the byte array to blob. – Raj Dec 28 '17 at 07:02
  • Please see this answer: https://stackoverflow.com/questions/5336239/attach-a-file-from-memorystream-to-a-mailmessage-in-c-sharp. Essentially you will create a memory stream from byte array. – Gaurav Mantri Dec 28 '17 at 07:06

2 Answers2

1

How can I fetch the file from Azure Blob and send it as an attachment?

Per my understanding, you could download your blob into a temp local file in your function as follows:

// Save blob contents to a file.
using (var fileStream = System.IO.File.OpenWrite(@"path\myfile"))
{
    blockBlob.DownloadToStream(fileStream);
}

Then, you could construct your Attachment as follows:

System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment("{file-path}");

Or you could directly download your blob into the MemoryStream as follows:

using (var memoryStream = new MemoryStream())
{
    blockBlob2.DownloadToStream(memoryStream);
    memoryStream.Position = 0;
    System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(memoryStream , "{contentType}");
}

Details you could follow Download blobs.

Bruce Chen
  • 18,207
  • 2
  • 21
  • 35
0
        var blob_Archive = Environment.GetEnvironmentVariable("blobName", EnvironmentVariableTarget.Process);
        var archiveSheetFile = $"{blob_Archive}/FileName-{DateTime.UtcNow:ddMMyyyy_hh.mm}.csv";

        using (var txReader = await binder.BindAsync<TextReader>(
        new BlobAttribute(file2read, FileAccess.Read)))
        {
            if(txReader != null)
            sBlobNotification = await txReader.ReadToEndAsync();
        }
        log.LogInformation($"{sBlobNotification}");

you can write the above code in timer trigger function and get the blob content. Does this helps!!

Deepak Shaw
  • 461
  • 3
  • 6