Cleaning up after sending SMTP mail in Powershell

I like exporting and sending the results of my Powershell scripts via SMTP mail.  That obviously require some sort of temporary location to hold my data while I am working on things.  However, I also try to stay away from dumping the temporary contents into TEMP or TMP.  I want to keep my junk separate from everyone, know exactly what should be in my temporary environment at a given time and clean everything up when I am done.

To achieve that, I always have a temporary location in my code where I keep my junk.  When I started to use that in conjunction with my mail-enabled scripts, I found that my temporary location was not being cleaned up consistently.  It was a bit hit-and-miss!  For example: Suppose you have a script that has a temporary file location in it but also has mail sending code similar to this:

$SMTPClient = new-object system.net.mail.smtpclient
$MailMessage = new-object system.net.mail.mailmessage
$SMTPClient.Host = $SMTPHost
$MailMessage.From = $Sender
$MailMessage.To.Add($Recipients)
$MailMessage.Subject = "Some Random Subject" 
$MailMessage.Body = "Some Random Body"
$SMTPClient.Send($MailMessage)

You may find that if you try to cleanup your temporary files and folder after sending the mail, it might not work consistently.  It’s also possible that upon debugging, you come across an error: “The process cannot access the file ‘somefile.csv’ because it is being used by another process” or something similar.

This is because good .NET programming (which Powershell is based on) requires releasing the resources and file handles after using a class, in this case, after sending the mail.  So, to avoid the problem, simply add the method:

$MailMessage.Dispose()

after sending the mail and before the cleanup code.  This will release the resources that are held up in memory and the cleanup should be successful.

Hope this helps!

By | 2016-12-11T15:25:09+00:00 April 3rd, 2010|Powershell|2 Comments

About the Author:

2 Comments

  1. Mathieu Bouffard September 13, 2012 at 9:42 AM - Reply

    Thanks! that was exactly my issue!
    Was trying to move my logfile at the end of the script, just after sending it by mail. Now it works.

Leave A Comment