Sending email from Microsoft Windows PowerShell through SparkPost

May 17, 2019 Contributors

This article helps you develop and test SMTP injection scripts under Microsoft Windows. Here we concentrate on the basic (but usable) Windows PowerShell built-in features for sending via SMTP.

If you need more options, check out cross-platform tools such as swaks ("Swiss Army Knife for SMTP").

Pre-requisites

There are a few things you need:

Create PowerShell script

PowerShell scripts are text files with a .ps1 extension.

The Send-MailMessage commandlet is available for PowerShell versions 3.0 through 6.0. It doesn’t have as many options as swaks, but you can set up the most important attributes such as To, From, Subject, Body, Server, Port and so on.

Windows by default tries to use TLS 1.0, which is widely deprecated as insecure and will not be accepted by SparkPost. We select TLS 1.2 instead using:

Credentials (username and password) need to be set up in a PSCredential object. The usual Windows behavior is to interactively prompt the user, however we choose to follow this approach and set it directly in the script.

The entire script file looks like this. Don’t forget to put in your API key value, sending domain, and recipient domain.

File: SparkPost_win_powershell_example.ps1

Run the script:

Comment lines begin with #. The backtick character ` is used to continue a command over several text lines.

It’s convenient to edit and run scripts using the ISE Editor. You can open this by selecting right-click “Edit” on your file.

The green triangle on the menu bar is the "run" button.

Your script execution is shown in the lower pane. If the mail sent OK, your command prompt returns without an error message.

Error messages

If there’s something wrong with your From, To, SmtpServer or Credentials settings, you’ll see an error message. For example, an invalid API key will give