Sending an e-mail with PowerShell

This is really useful if you want to test if a server is able to send out an e-mail through SMTP. Or just want to schedule a task to send out an e-mail once a month, Here are the details:

SMTP Ports
Normally 25 (not secure)
465 (SSL)
587 (TLS)

Basic PowerShell command to send e-mail
This can be run as a scheduled task to send youreslef a reminder

send-mailmessage -from "webserver1 <webserver1@me.com>" -to "support <support@me.com>" -subject "Reminder to do something" -body "Please assign to me. `r`n`r`n Create a ticket to me" -smtpServer smtp.mysmtpserver.com

Advanced PowerShell script to send e-mail
This can be found online somewhere, i usually comment out the attachments section to test it out with a password and a specific port
Sendmail.ps1

$CredUser = "username"
$CredPassword = "password"

# Outgoing email configuration used for sending messages
$outgoingUsername           = "user"
$outgoingPassword           = "password"
$outgoingServer             = "SMTP.myserver.com"
$outgoingPortSMTP           = 587   # Normally 25 (not secure), 465 (SSL), or 587 (TLS)
$outgoingEnableSSL          = $true
$outgoingFromAddress        = "webserver1@me.com"
$outgoingToAddressList      = @( "myemail@me.com" )
$outgoingCCAddressList      = @()
$outgoingBCCAddressList     = @()
#$outgoingAttachmentURLList  = @(..\Attachments\File-01.pdf", "..\Attachments\File-02.svg)

# Use Send-MailMessage command to send an email
Write-Host "Sending message 1..."

$messageSubject = "Test Subject 1"
$messageBody = "This is a test message 1."

$tempPassword = ConvertTo-SecureString -String $outgoingPassword -AsPlainText -Force
$credential = New-Object -TypeName "System.Management.Automation.PSCredential" `
   -ArgumentList $outgoingUsername, $tempPassword

Remove-Variable -Name tempPassword

$parameters = @{
   "From" = $outgoingFromAddress;
   "Subject" = $messageSubject;
   "Body" = $messageBody;
   "SmtpServer" = $outgoingServer;
   "Port" = $outgoingPortSMTP;
   "UseSsl" = $outgoingEnableSSL;
   "Credential" = $credential
   }

if ( $outgoingToAddressList )
   {
   $parameters.add( "To", $outgoingToAddressList )
   }

if ( $outgoingCCAddressList )
   {
   $parameters.add( "CC", $outgoingCCAddressList )
   }

if ( $outgoingBCCAddressList )
   {
   $parameters.add( "BCC", $outgoingBCCAddressList )
   }

if ( $outgoingAttachmentURLList )
   {
   $parameters.add( "Attachments", $outgoingAttachmentURLList )
   }

Send-MailMessage @parameters
This entry was posted in Microsoft, Scripting. Bookmark the permalink.

Leave a Reply

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