How to send emails from Powershell using an SMTP Service

In this scenario, we are going to use a Powershell Script to send emails using a popular service like Gmail.

Removing the Additional security on Gmail

Gmail offers an extra layer of security regarding sending emails from scripts called “less secure Applications,” for this reason, we go to the following URL: https://myaccount.google.com/lesssecureapps and move the slider to the right to allow this configuration like this:

IMPORTANT NOTE:

if you are not using this application anymore, I recommend disabling such Access since it blocks any exploit you can have on your account, and it’s better to have more security than less.

Running the script

Before you can run the script without issues, you’d need to make sure the Powershell Policy is unrestricted

  • Open up Powershell as Administrator
  • Run the following command: Set-ExecutionPolicy Unrestricted
  • Accept the change by pressing “O” and then enter.
  • You can close Powershell and open it back in regular windows (no Admin privileges are required).

Finally, you’d need to use this script; you can copy and paste it into a Text file on your desktop called “Send-SMTPemail.ps1”

$From = “jortega928@gmail.com”

$To = “jortega@faboit.com”

#$Attachment = “C:\temp\Some random file.txt”

$Subject = “Email Subject From Powershell Script”

$Body = “<h1>Hello from Powershell Stream</h1><h3>It really works</h3>”

$SMTPServer = “smtp.gmail.com”

$SMTPPort = “587”

#$creds = Get-Credential

Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort -Credential $creds -UseSsl -BodyAsHtml #-Attachments $Attachment

Make sure to update the following values:

  • “From” (the person that sends out email),
  • “to” (that receives the email)
  • Subject (Email Subject)
  • Body (Email Body as HTML)
  • SmtpServer ( SMTP server enabled to send emails)
  • Port (make sure that is working on 587, 465, or for unauthenticated 25).

There is a 5 min video at https://www.twitch.tv/videos/621535278

There is a full 1 hr stream of using this and another script at https://www.twitch.tv/videos/621492355 (This is on the last 5 mins).

Thank you for reading it.

Follow me| Help me grow | MCP | MCSE| MS Technical Lead Exchange Online/Powershell | Experts-Exchange Awarded 2018 | TechNet 66k Downloads.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store