Send-MailMessage closes every 2nd connection when using attachments

戏子无情 提交于 2019-12-06 05:50:12

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!