In PowerShell, is there a way to dispose of Send-MailMessage resources?

Viewed 1473

I've written a PowerShell script that sends an email message. Originally I used the Send-MailMessage commandlet.

Send-MailMessage -SmtpServer $MailServer `
-To $MailTo `
-From $MailFrom `
-Subject $MailSubject `
-Body $MailBody

This is concise. But if I execute the script rapidly in succession on my workstation, the following error appears in the PowerShell console.

Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.

What I suspect is that resources aren't being released or that a thread is getting blocked. Below is my current workaround, which has the advantage of being disposable. And I can run this in rapid succession with no transport connection errors. But this is more verbose than Send-MailMessage.

[object]$SMTPClient = New-Object System.Net.Mail.SmtpClient
[object]$MailMessage = New-Object System.Net.Mail.MailMessage
$SMTPClient.Host = $MailServer
$MailMessage.To.Add($MailTo)
$MailMessage.From = $MailFrom
$MailMessage.Subject = $MailSubject
$MailMessage.Body = $MailBody
$SMTPClient.Send($MailMessage)
$MailMessage.Dispose()
$SMTPClient.Dispose()

Is there some way to force Send-MailMessage to release resources when I'm done with it, perhaps via Dispose or a C# style using statement? Thanks.

2 Answers
Related