It’s late on a Friday night. Like most people, you have somewhere else you would rather be. Instead, you are stuck at work because you completely forgot about some scheduled maintenance that has to be done that night.
You’re familiar enough with PowerShell to make some scripts to take care of the maintenance, but you’re worried about the off-chance that one of the scripts fails or you’re worried that something could go wrong.
Wouldn’t it be great if you could start your scripts and configure them to email you the results? You could still get out, enjoy your Friday night and rest assured that your scripts are doing their job without you losing yours!
(Disclaimer: We do not condone the shirking of any responsibilities that you may have…especially on Friday nights.)
Sending Email with PowerShell (Send-MailMessage)
There are a multiple ways to send an email with PowerShell. This is a native cmdlet option that is simple and easy to use. It uses the cmdlet Send-MailMessage.
Send-MailMessage <parameters>
List of available parameters
Examples of Usage:
Example 1) Sending a simple email
Send-MailMessage -From "[email protected]" -To "[email protected]" -Credentials (Get-Credential) -SmtpServer "smtp.yourdomain.com"
Example 2) Sending an email from Gmail
Here’s a full example of sending an email via Gmail’s SMTP servers. It will prompt you for a username and password thanks to (Get-Credential). The username needs to be and password needs to be , though you could always pipe in a PSCredential and get the same effect.
##############################################################################
$From = "[email protected]"
$To = "[email protected]"
$Cc = "[email protected]"
$Attachment = "C:\temp\Some random file.txt"
$Subject = "Email Subject"
$Body = "Insert body text here"
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential (Get-Credential) -Attachments $Attachment
##############################################################################
Best of luck to you in your emailing endeavors.
Did you know that PDQ Deploy has a PowerShell step you can use to deploy your scripts?