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

I wrote a PowerShell script that sends an email message. I originally used the Send-MailMessage cmdlet.

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

      

It's short. But if I quickly execute the script on my workstation, the following error appears in the PowerShell console.

Unable to read data from transport connection: The established connection was interrupted by software on your host machine.

I suspect the resources are not released or the thread is blocked. Below is my current solution, which has the advantage of being one-off. And I can run it quickly with no network connection errors. But this is in more detail 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 a way to get Send-MailMessage to release resources when I'm done with it, perhaps using Dispose or C # style using a statement? Thank.

+3


source to share


2 answers


To be honest, "it works, but it's verbose" shouldn't be a big problem, especially when "verbose" means 10 lines. And I mean, you can simplify your syntax with class constructors:



$SMTPClient = New-Object -TypeName System.Net.Mail.SmtpClient -ArgumentList $MailServer
$MailMessage = New-Object -TypeName System.Net.Mail.MailMessage -ArgumentList $MailFrom, $MailTo, $MailSubject, $MailBody
$SMTPClient.Send($MailMessage)
$MailMessage.Dispose()
$SMTPClient.Dispose()

      

+4


source


Based on the comment, you can overflow any buffer the cmdlet has. This answer is more future-proof (less chance of bugs) using splatting:

$MailMessage = @{
  SmtpServer = $MailServer;
  To         = $MailTo;
  From       = $MailFrom;
  Subject    = $MailSubject;
  Body       = $MailBody;
}

Send-MailMessage @MailMessage

      



Edit-
This can also be done with the selected answer:

$Client = @{
  TypeName = 'System.Net.Mail.SmtpClient';
  ArgumentList = $MailServer;
}
$Message = @{
  TypeName = 'System.Net.Mail.MailMessage';
  ArgumentList = @($MailFrom,$MailTo,$MailSubject,$MailBody);
}
$SMTPClient = New-Object @Client
$MailMessage = New-Object @Message

      

+2


source







All Articles