Sending Email with PowerShell

Largely taken from here and here, the following example shows how to use PowerShell to send email, using the Gmail smtp server as an example:

$From = ""
$To = ""
$Cc = ""
$Attachment = "C:\Path\to\file.txt"
$Subject = "Email Subject"
$Body = "Insert body text here"
$SMTPServer = ""
$SMTPPort = "587"
Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject 
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl 
-Credential (Get-Credential) -Attachments $Attachment

Fill in the variables and go!

If you would like to pass your credentials in the script (not the most secure way to do things…), add two more variables, $password and $mycreds, and substitute the (Get-Credential) for $mycreds:

$password = ConvertTo-SecureString "YourPlainTextPassword" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("YourUsername", $password)
Send-MailMessage -From $From -to $To -Subject $Subject 
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl 
-Credential $mycreds -Attachments $Attachment

Leave a Reply

Your email address will not be published. Required fields are marked *