I am attempting to write a powershell script to send email with a few attachments to 30 people. The emails are personalized, so they must be sent individually. The script wo
The error seems to indicate a transport layer issue. Without knowing your network architecture it's a little tough to know for sure. Try this:
Maybe add a wait to your foreach loop to see if there is a server that is throttling (for lack of better word) your messages. Without access to the server config, your hack is likely the best you can do with this.
As far as your try/catch solution, that is going to produce the fastest success on your end, however, it will increase network traffic. You are essentially brute forcing your way past whatever limits you are hitting.
I believe I have found the best available solution to this. Big thanks to @Matt for helping me with this in the comments.
It seems like the issue spawns from Send-Mailmessage
not properly disposing the connection object once it finishes sending mail. Running Send-Mailmessage
with an existing connection forces it to be disposed, and thus running it for a third time results in success.
The workaround is running each instance of Send-Mailmessage
as a separate job. To quote @Matt:
PowerShell jobs have their own memory and resources. When the job is done that memory is supposed to be removed.
As a result, each time we run Send-Mailmessage
as a job, the connection is properly created and disposed. I am also piping this to Wait-Job | Receive-Job
to naturally rate-limit, view output, and prevent any memory issues that could maybe be theoretically possible.
Start-Job -ScriptBlock {
Send-MailMessage -From 'mymail' -To 'theirmail' -SmtpServer 'fqdn' -Attachments "$($args[0])\1.pdf", "$($args[0])\2.pdf" -Subject 'subject' -Body ("test")
} -ArgumentList $PSScriptRoot | Wait-Job | Receive-Job
Using this method produces no errors, and should reduce load on the SMTP server.