How to use Gmail to send PowerShell script notifications

Gmail allows the use of SMTP, we can use SMTP for sending e-mail notifications from within PowerShell.

The first step is to register an e-mail address at Gmail. This is a very straight forward step so this will not be included in this blog post.

So, when you have registered with Gmail we can add the following code to our PowerShell script:

 

$username = “your-registered-address@gmail.com“
$password = ConvertTo-SecureString ‘yourpassword‘ –asplaintext –force

$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password

Send-MailMessage -From yourgmailaddress@gmail.com -Subject Test -To receiver@address.com -Body `
“
The script has finished.
And this is the second line.
” `
-Credential $cred -Port 587 -SmtpServer smtp.gmail.com -UseSsl | out-null

Now, when you execute this PowerShell code it will send an e-mail with the notification that the script has finished.

The first time you use PowerShell to send an e-mail it could be that Gmail does not allow this. This is due to the fact that the security settings are set to high.
When this is the case, Gmail will send you an e-mail where you can allow the use of SMTP by decreasing the security settings.

Advertisements
This entry was posted in Scripts and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s