SendGrid SMTP using Powershell and REST API
Sendgrid stopped accepting account username
and password
. I was using powershell cmdlet send-mailmessage to run some of auditing scripts from VM’s and it all broken due to this. Final solution with out much modification our script is done by setting username as apikey and password as APIKEYVALUE. Details of the same is available with SendGrid Support page
Let me know if this helps you. You can reach me on twitter for any queries.
<# | |
.SYNOPSIS | |
This function will enable you to send mail with SendGrid without using 'Send-MailMessage' | |
.DESCRIPTION | |
Azure VM's sending mail with 'Send-MailMessage' cmdlet reported failure. Hence new script is created to handle this. | |
This script works by calling send grid v3 rest API | |
.EXAMPLE | |
PS . <pathToThisFunctionps> | |
Then you can invoke this script natively in any other scripts | |
.INPUTS | |
Inputs | |
-From[String Array] - From emailaddress | |
-To[String Array] - To email address | |
-ApiKey - Sendgrid API key | |
-Subject - Mail header subject | |
-Body - Mail Body | |
-FilePath - Attachment file path | |
.OUTPUTS | |
Output (if any) | |
.NOTES | |
#ToDo | |
Multiple attachments Array. | |
#> | |
function Send-EmailWithSendGrid { | |
Param | |
( | |
[Parameter(Mandatory = $true)] | |
[string] $From, | |
[Parameter(Mandatory = $true)] | |
[String[]] $To, | |
[Parameter(Mandatory = $true)] | |
[string] $ApiKey, | |
[Parameter(Mandatory = $true)] | |
[string] $Subject, | |
[Parameter(Mandatory = $true)] | |
[string] $Body, | |
[Parameter(Mandatory = $true)] | |
[string] $FilePath | |
) | |
$toEmailAddr = $null | |
$toEmailAddr = @() | |
foreach($to in $toAddr){ | |
$toEmailAddr+= @{"email" = "$to"} | |
} | |
$headers = @{ } | |
$headers.Add("Authorization", "Bearer $apiKey") | |
$headers.Add("Content-Type", "application/json") | |
$attachments = (Get-Item $FilePath) | |
$content = [Convert]::ToBase64String([IO.File]::ReadAllBytes($FilePath)) | |
$jsonRequest = [ordered]@{ | |
personalizations = @(@{to = @($toEmailAddr) | |
subject = "$SubJect" | |
}) | |
from = @{email = "$From" } | |
content = @( @{ type = "text/plain" | |
value = "$Body" | |
} | |
) | |
attachments = @( | |
@{ | |
content = $content | |
filename = $attachments.Name | |
} | |
) | |
} | ConvertTo-Json -Depth 10 | |
Invoke-RestMethod -Uri "https://api.sendgrid.com/v3/mail/send" -Method Post -Headers $headers -Body $jsonRequest | |
} | |