Sending automated emails using Powershell

Hello,
Let me share the code that I have used to automatically sent out emails using PowerShell. You can use Windows Task Scheduler to automate its execution.

#Program to send test emails
$counter = 0;

$LogPath = “C:SendEmailsToolSend Test EmailsLog.txt”

“Program started at $(Get-Date)” | Out-File -FilePath $LogPath -Append

$emailfrom = “Richmond Times-Dispatch <no-reply@richmond.com>”

$emailTo = “email@destination.com”

$smtpserver = “internal-smtp”

$smtp = new-object Net.Mail.SmtpClient($smtpServer)

while ($counter -le 0){

try{

$emailSubject = “Testing email #” + $counter + “”;

$body = “This is another test # ” + $counter + ” Please ignore.`r`n”

$smtp.Send($emailfrom, $emailTo, $emailSubject, $body)

$counter++;

Start-Sleep -Milliseconds 1000

}

catch{
“Caught an exception:” | Out-File -FilePath $LogPath -Append
“Exception Type: $($_.Exception.GetType().FullName)” | Out-File -FilePath $LogPath -Append
“Exception Message: $($_.Exception.Message)” | Out-File -FilePath $LogPath -Append
$caughtException = $true

}

}

“Program completed at $(Get-Date) =======” | Out-File -FilePath $LogPath -Append

 

2 thoughts on “Sending automated emails using Powershell”

Leave a Comment

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