Skip to content

Instantly share code, notes, and snippets.

@pkskelly
Created December 2, 2015 20:30
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • 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 = "admin@acme.com"
$EmailTo = "user@acme.com"
$Subject = "SendGrid test"
$Body = "SendGrid testing successful"
Send-MailMessage -smtpServer $SMTPServer -Credential $credential -Usessl -Port 587 -from $EmailFrom -to $EmailTo -subject $Subject -Body $Body
@anupamdas24
Copy link

How to add the attachment file while sending the mail in SendGrid using powershell

@vjsimha1
Copy link

How to add the attachment file while sending the mail in SendGrid using powershell

You can add a parameter "-Attachments" to the Send-MailMessage cmdlet and specify a comma separated list of file names.

@msniral
Copy link

msniral commented Jul 3, 2020

Sending passwords over the script is not secure, instead, use API Keys provided by SendGrid to send emails with or without attachments

@kumammanish
Copy link

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.

@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.

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