Path Property string Path
To demonstrate the flexibility of variables we can reverse the string and print the path backwards.
Saving scripts and executing files
When you want to run a complicated set of instructions it is best to write them into a file line by line and save it as a powershell script with the
extension. You can then invoke the script using the
prefix. For instance if you have a
run it from Powershell with the command
To send emails the simplest way is to use the
command. The method documentation looks like this:
Each bracket contains an argument that can be passed to the command. To use the command to send email in Powershell we must first obtain access to an SMTP mailserver. The SMTP server will receive our mail send request and send the email to the desired destination using the SMTP protocol. Normal mail clients tend to use IMAP and POP3 but pretty much ever server will support SMTP so check with your provider.
Configuring SMTP access
Powershell reads a variable for SMTP access when you send emails called
. Set this value before sending like so:
Or by passing arguments to the send command:
Composing emails with Powershell
To send an email with Powershell include your destination recipients and a message body. A simple message might look like this:
Send attachments with Powershell
You can read files with Powershell and attach them to your email by creating a new object
with the file path. Here is an example
script showing how to include files in your email.
When not to use Powershell (security concerns)
Powershell is great but has some drawbacks when sending emails. According to Microsoft the Send-MailMessage is obsolete and no longer recommended as it cannot guarantee secure connections. For that reason it is important to consider some alternatives such as the free Powershell package MailSlurp. Running Send-MailMessage confirms this by printing the warning below:
Alternative methods for sending email in Powershell
A great way to send emails in Powershell without using the Send-MailMessage command is by using a free and secure email API service like MailSlurp. MailSlurp offers SMTP mail servers with custom API access so you can send and receive emails in any scripting environment using secure connections. The first step is to sign up and obtain a free API Key.
Then create a new inbox email address to send emails with. Save the inbox ID as this is important for the next step:
Send email using Invoke-WebRequest
To send an email using MailSlurp simply make an HTTP/S POST request and pass the message parameters as JSON:
Running the script returns a 201 status code if successful.
Conclusion and next steps
Powershell is a great way to automate tasks including the sending of emails and attachments. Use the
command to send emails and attachments using your own SMTP server. If you don't have one or need a more secure solution use an email API service like MailSlurp and the
method to send your payload.