Skip to content

Instantly share code, notes, and snippets.

@pkskelly
Created December 2, 2015 20:30
Show Gist options
  • Save pkskelly/0b16f9892234e88c50c3 to your computer and use it in GitHub Desktop.
Save pkskelly/0b16f9892234e88c50c3 to your computer and use it in GitHub Desktop.
Sending Email from PowerShell using SendGrid (in Azure)
$Username ="azure_*********@azure.com"
$Password = ConvertTo-SecureString "********" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $Username, $Password
$SMTPServer = "smtp.sendgrid.net"
$EmailFrom = "[email protected]"
$EmailTo = "[email protected]"
$Subject = "SendGrid test"
$Body = "SendGrid testing successful"
Send-MailMessage -smtpServer $SMTPServer -Credential $credential -Usessl -Port 587 -from $EmailFrom -to $EmailTo -subject $Subject -Body $Body
@msniral
Copy link

msniral commented Jul 10, 2020

Using API Keys with PowerShell, for sending attachments is the tricky part. SendGrid documentation too does have much on this. Can any one help here.

You can store the API Keys in KeyVault and retrieve the same from it.

$SENDGRID_API_KEY = (Get-AzKeyVaultSecret -VaultName $VaultName -Name $ApiKeyName).SecretValueText
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Bearer " + $SENDGRID_API_KEY)
$headers.Add("Content-Type", "application/json")

create a body json which has mail body content which has from and destination mail address details, subject and bodyContent of Mail
finally, call the below method.

$response = Invoke-RestMethod -Uri https://api.sendgrid.com/v3/mail/send -Method Post -Headers $headers -Body $bodyJson

@projectje
Copy link

The operation has timed out.

@parlevjo2
Copy link

Thanks. Nice Script. Works perfect. Only one thing 1 had changed.
$Username ="azure_*********@azure.com"
should be
$Username ="apikey"
Username is always apikey
The password defines the configuration in Sendgrid

@msniral
Copy link

msniral commented Jul 31, 2024 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment