powershellmailmessage

PowerShell still locks the file after the end of a script that sends email with attachment


I'm using PowerShell and System.Net.Mail.MailMessage to create email body with an attachment. I found after the end of my script and the email is sent successfully, the target file is still occupied by PowerShell until I exit PowerShell. Is there any way to "close" it like closing file pointer in C or Python?

Here is the code of how I create mail message and send it:

$message = New-Object System.Net.Mail.MailMessage $sender, $mailTo
$message.Subject = "Test email with attachment"
$message.Body = "See attachment."
$message.Attachments.Add("path\to\file")

$smtpClient = New-Object Net.Mail.SmtpClient($smtpHostname, $smtpPort)
$smtpClient.EnableSSL = $true
$smtpClient.send($message)

Solution

  • Both System.Net.Mail.MailMessage and System.Net.Mail.SmtpClient implement the IDisposable interface, which means you can - and should[1] - call the .Dispose() method on their instances to make them release all resources they may be using once you're done:

    $message.Dispose()
    $smtpClient.Dispose()
    

    [1] If you neglect to do so, the resources held will eventually be released, namely the next time .NET's garbage collector runs, but the timing of that isn't predictable.