Search code examples
azureazure-devopsazure-powershellazure-automationazure-runbook

Powershell Runbook Email with the csv file attachment


I want to send an email from my powershell runbook script, I wouild like to attach CSV file as the script output which is stored in storage blob on my azure subscription.

The script is ready, I am receiving email but without attachment. I am still facing the issue, and when I am executing script from Azure automation, as a runbook, I can see below error message. I am storing all files in the same container.

New-Object : Exception calling ".ctor" with "1" argument(s): "Could not find file 'C:\Users\Client\Temp\xxxxxxxx.csv'."

this is my output --> $ArrayStatus | Export-Csv -NoTypeInformation -Path "$filename"

$filename is a CSV file location

$ArrayStatus | Export-Csv -NoTypeInformation -Path "$filename"
Get-AzureStorageBlob -Container "xxx" -Blob "$filename" -Context $Context 
Get-AzureStorageBlobContent -force
$attachment = "$filename"

Function Email ($EmailTo, $Body){
$EmailFrom = "xxx"
$Subject = "xxx Alert" 
$SMTPServer = "xxx" 
$SMTPMessage = New-Object 
System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attach = New-Object System.Net.Mail.Attachment($attachment)
$SMTPMessage.Attachments.Add($attach)
$SMTPMessage.IsBodyHTML = $false
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, xx) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("xx", 
"xx");  
$SMTPClient.Send($SMTPMessage)
            }

I am receiving email but without CSV file attachment


Solution

  • Provided you have uploaded the output of export-csv to Azure blob storage using Set-AzureStorageBlobContent successfully. You can use the below snippet to read the blob from storage container and store it to local destination and get contents of the file and send an email as attachment.

    # Setting the Azure Storage Context,recommedation is to read sastoken from Runbook assets for security purpose.
    $context = New-AzureStorageContext -StorageAccountName "storageaccountname" -SasToken "your storage account sastoken"
    
    # Get the blob contents from storage container and store it local destination . 
    Get-AzureStorageBlob -Container "containername" -Blob "filename.csv" -Context $context | Get-AzureStorageBlobContent -force -Destination .
    
    #Get contents of the file
    $attachment = Get-Content "filename.csv"
    
    #send an email (provided the smtp server is reachable from where ever you are running this script) 
    Send-MailMessage -From '[email protected]' -To '[email protected]' -Subject 'Content from Blob Storage' -Body "CSV File from Storage blob, sending an attachment for testing" -Attachments .\filename.csv -Priority High -DeliveryNotificationOption OnFailure -SmtpServer 'smtpserver'
    

    Hope this helps.