QuickTip: Sending email using REST API
I will start this tip with a use case. A cloud ops team member reached out to me seeking help with sending out a report from a script he had that collected Citrix data using REST API. He wanted to embed the capability to send email right into his script that was written in Powershell. Now there are many ways to send emails within Powershell but this script had some unique requirement so we choose to use Twilio SendGrid. Anybody who has used Output bindings with Azure Function Apps and Azure devops may have already used Twilio SendGrid.
The code
$Body=@{
"personalizations" = @(
@{
"to" = @(
@{
"email" = "myemail@hotmail.com"
"name" = "Gurpreet Singh"
}
)
"subject" = "Test Email from Twilio SendMail"
}
)
"content" = @(
@{
"type" = "text/html"
"value" = ("<html><p>Computer: {0}</p><p>{1}</p><br></html>" -f $env:computername, "Test Email from Twilio SendGrid")
}
)
"from" = @{
"email" = "myemail@lessergeek.com"
"name" = "Gurpreet Singh"
}
}
$BodyJson = $Body | ConvertTo-Json -Depth 4
$token = "SG.YlV9LRfbSdKGmH0Q5UBvFw.-09-GetYourOwnKeyQ-nFcuf7ZUp8Xw5qjBHP_B"
$Header = @{
"authorization" = "Bearer $token"
}
#send the mail through Sendgrid
$Parameters = @{
Method = "POST"
Uri = "https://api.sendgrid.com/v3/mail/send"
Headers = $Header
ContentType = "application/json"
Body = $BodyJson
}
Invoke-RestMethod @Parameters
The code defines an array object of hash table containing email and name of the recipients, Subject of the email, content, who the email is from.
Note: Change the Token in the above code as it is a dummy value only. Create a token in Twilio Sendgrid and authorize the sender used in the “from” object.
More Tips
- Twilio SendGrid azure resource can be created from Azure. The free account allows you to send 100 emails per day. Once your 100 email limit is hit you would be charged a certain amount per email. so if you have an issue in your code and the code ends up sending out thousands of emails in a badly written code your Azure Bill could be significant. To ensure this does not happen, create an account directly from their website or simply code carefully.
- There are many other similar services that use REST API and allow more free emails per day.
- You need to authorize the sender email so it must be a valid email address.
- You may not be able to use same email address in the “from” and “to” objects. Most mail systems will send these emails to spam.
- Protect the code by storing and fetching the token from a secure location like keyvault, secure variables in devops etc. The code above has the token in plain text in the above sample which is only for demonstration purposes and cannot be deemed safe.
- remember to limit the permissions assigned to the token you create in sendgrid. In my case I just assign send email permissions only as shown in the screenshot below. If your intent is just to send out emails, you do not need to provide full access to the token being created.