0

I would like to send bulk e-mail via powershell from exchange server. I found this script on the net which is what I was looking for. However, to avoid spam blocking, I would like to send a few thousand emails in a controlled space of time.

How can I add a line for Time Between Emails? I would like the script to send one e-mail every 10 second.

Can you help? Thanks

$thisScript = $myInvocation.MyCommand.Path
$scriptRoot = Split-Path(Resolve-Path $thisScript)
$recipientsListFile = Join-Path $scriptRoot "recipientsList.txt"
$EmailBodyFile = Join-Path $scriptRoot "EmailBody.txt"

$arrEmailBody =@()
$arrEmailBody += Get-Content $EmailBodyFile
$strsmtp = "<SMTP Server>"
$strSubject = "<Email Subject>"
$fromEmail = "<Sender's Email>"
$fromName = "<Sender's Name>"
$Sender = New-Object System.Net.Mail.MailAddress($fromEmail, $fromName)

$port = 25

$SMTPClient = New-Object System.Net.Mail.smtpClient
$SMTPClient.host = $strsmtp
$SMTPClient.port = $port


foreach ($item in (Get-Content $recipientsListFile))
{
    $MailMessage = New-Object System.Net.Mail.MailMessage
    $strName = ($item.split(";"))[0]
    $strEmail = ($item.split(";"))[1]

    $strBody = @"
Dear $strName


"@
    Foreach ($line in $arrEmailBody)
    {
        $strBody = $strBody + @"
        $line

"@
    }

    $objRecipient = New-Object System.Net.Mail.MailAddress($strEmail, $strName)
    $MailMessage.Subject = $strSubject
    $MailMessage.Sender = $Sender
    $MailMessage.From = $Sender
    $MailMessage.To.add($objRecipient)
    $MailMessage.Body = $strBody
    $SMTPClient.Send($MailMessage)
    Remove-Variable objRecipient
    Remove-Variable mailMessage
}
Otter
  • 1,086
  • 7
  • 18
SDJAnu
  • 1
  • 1
    Have you had a look into the `start-sleep` [cmdlet](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/start-sleep?view=powershell-7.2), Try adding that to the second last line. That then should wait for the specified amount of time before moving on to the next recipient – Otter Jun 03 '22 at 10:01

1 Answers1

0

Because you are already in loop iterating through each recipient, you can just add a wait to the end of the loop.

You can do this by adding Start-Sleep -Seconds 10 to the second last line of your script.

    ...    
    Remove-Variable objRecipient
    Remove-Variable mailMessage
    Start-Sleep -Seconds 10
}
Otter
  • 1,086
  • 7
  • 18