Send-SendGridMail.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

<#PSScriptInfo
.VERSION 1.0
.GUID b0ae5b5c-b14b-42cb-ae0b-cd46c97000da
.AUTHOR Thomas Zuehlke
.COMPANYNAME
.COPYRIGHT
.TAGS AzureAutomation Mail SendGrid
.LICENSEURI
.PROJECTURI https://blog.zuehlke.cloud/2020/07/send-mails-with-sendgrid-via-azure-automation/
.ICONURI
.EXTERNALMODULEDEPENDENCIES
.REQUIREDSCRIPTS
.EXTERNALSCRIPTDEPENDENCIES
.RELEASENOTES
.PRIVATEDATA
#>


<#
.SYNOPSIS
   Send Mails by using the SendGrid service in Azure.
 
.DESCRIPTION
   Loads the SendGrid API-Key from Azure Automation secrets and creates a body for a post message by using the parameter. Sends the message via post.
 
.PARAMETER SendGridApiCredentialName
   Mandatory
   The name of the credentials, where the SendGrid-API Key is stored.
 
.PARAMETER To
   Mandatory
   Mail receiver.
 
.PARAMETER From
   Mandatory
   Mail sender
 
.PARAMETER Subject
   Mandatory
   Mail subject
 
.PARAMETER Body
   Mandatory
   Mail body
 
.PARAMETER SendGridApiUrl
   Optional
   REST URL
 
.NOTES
   AUTHOR: Thomas Zuehlke
   LASTEDIT: July, 2020
#>
 
# Returns strings with status messages
[OutputType([String])]

param (
    [Parameter(Mandatory=$true)] 
    [String]  $SendGridApiCredentialName,

    [Parameter(Mandatory=$true)] 
    [String] $To,
    
    [Parameter(Mandatory=$true)] 
    [String]  $From,

    [Parameter(Mandatory=$true)] 
    [String]  $Subject,

    [Parameter(Mandatory=$true)] 
    [String]  $Body,
    
    [Parameter(Mandatory=$false)] 
    [String]  $SendGridApiUrl = "https://api.sendgrid.com/v3/mail/send"
)

$Cred = Get-AutomationPSCredential -Name $SendGridApiCredentialName
$userName = $Cred.UserName
$securePassword = $Cred.Password
$ApiCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, $securePassword
$ApiKey = $ApiCred.GetNetworkCredential().Password

$Config = '{"personalizations": [ { "to": [ { "email": "'+$To+'" } ], "subject": "'+$Subject+'" } ], "from": { "email": "'+$From+'" }, "content": [ { "type": "text/html", "value": "'+$Body+'" } ] }'

$Headers = @{"Authorization" = "Bearer " + $ApiKey}
$Result = Invoke-WebRequest -Uri $SendGridApiUrl -Method Post -ContentType "application/json" -Body $Config -Headers $Headers -UseBasicParsing

return $Result