Custom MailMessage

Extend and improve the standard Send-MailMessage cmdlet.

— Binary Adventures

Here’s a module that builds on the Send-MailMessage cmdlet and extends the functionality, specifically with regards to the attachments.

I wrote this code in order to send a notification via mail (e.g. when an error occurs) and simultaneously include the relevant logs, thereby saving the recipients the effort in having to look for the logs themselves.

I generate my logs using the Start-Transcript cmdlet. However, if you try to include the currently open transcript as an attachment, you’ll be faced with the error:

Send-MailMessage : The process cannot access the file 'C:\temp\transcript.log' because it is being used by another process.

Log files can be rather large in size as well, and SMTP servers tend to reject messages that exceed a certain size. As log files are pure text, they are ideal candidates for compression.

So what does it do?

Here’s the gist of it:

  • Attachments are copied to a temporary folder before being sent, thereby avoiding the used by another process error message. Whatever the outcome, the temporary folder is removed at the end.
  • Using the parameter -CompressAttachments, all attachments will be compressed into a single archive.
  • If compression fails for whatever reason, the original (uncompressed) files will be sent.
  • The mail body is sent as HTML, and at the top, a boilerplate notice is added explaining that this is an automated mail.
  • If Send-MailMessage fails, a warning is shown but the exception is not propagated to the calling code. This is on purpose: the mail is sent as a separate, independent action and should not impact the main code.