Using Sendgrid with Powershell

Create a sendgrid account at https://sendgrid.com/

Download nuget.exe from https://www.nuget.org/nuget.exe and save it in some folder where sendgrid will be installed.

Run ‘nuget.exe install sendgrid’ on command line from the path where nuget.exe is saved. Two sendgrid folders will be created with structure like below in the same directory from where the command is run. No need to use Run as administrator option.

  • Sendgrid.6.1.0\lib\SendGridMail.dll
  • Sendgrid.6.1.0\Sendgrid.6.1.0.nupkg
  • SendGrid.SmtpApi.1.3.1\lib\net40\SendGrid.SmtpApi.dll
  • SendGrid.SmtpApi.1.3.1\lib\portable-net4+wp81\SendGrid.SmtpApi.dll
  • SendGrid.SmtpApi.1.3.1\SendGrid.SmtpApi.1.3.1.nupkg

These folders are downloaded by nuget from https://github.com/sendgrid/sendgrid-csharp which is official location for SendGrid C# libraries.

This install option will not add these assemblies to GAC so you will need to use either Add-Type or [Reflection.Assembly]::LoadFrom(…)  option to load these libraries in session or script. Overall Code would be like below

$SGMail= [Reflection.Assembly]::LoadFile("C:\Software\Sendgrid.6.1.0\lib\SendGridMail.dll")
$SGSMTP= [Reflection.Assembly]::LoadFile("C:\Software\SendGrid.SmtpApi.1.3.1\lib\net40\SendGrid.SmtpApi.dll")</code>

$myMessage = New-Object -TypeName:SendGrid.SendGridMessage
$myMessage.From = New-Object System.Net.Mail.MailAddress("user@example.com");
$recipients = @("Another user &lt;Anotheruser@AnotherDomain.com&gt;")
$myMessage.AddTo($recipients);
$myMessage.Subject = "Testing the SendGrid Library"

$myMessage.Html = "&lt;p&gt;Hello World!&lt;/p&gt;"
$myMessage.Text = "Hello World plain text!"

$username = "sendgridusername"
$password = "sendgriduserpassword"
$credentials = New-Object -TypeName:System.Net.NetworkCredential -ArgumentList:$username,$password

$TransportWeb = New-Object -TypeName:Sendgrid.web -ArgumentList:$credentials
$returnval = $TransportWeb.DeliverAsync($myMessage)
$returnval

Easiest way to figure out the exported classes from Sendgrid DLLs is to load these as reference in a VS 2015 VC# windows console app where you can then use Object browser to access all classes exported by these DLLs. Powershell has a convoluted way to show that but no point wasting time behind that when VS Community 2015 is free for all.

Definitely, this is not most secure code, but it works. Also, do remember that using this for internal organizational mails may be security risk since Sendgrid SMTP server would be transmitting it and thus they can have access to all your mails.

two Sendgrid classes used here are Sendgrid.sendgridmessage and Sendgrid.web. System.web is not getting used as that may seem look like from Sendgrid Github example.