Send-MailMessage closes every 2nd connection when using attachments

后端 未结 2 432
温柔的废话
温柔的废话 2021-01-15 03:45

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

2条回答
  •  爱一瞬间的悲伤
    2021-01-15 04:44

    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.

提交回复
热议问题