Skip to content

Instantly share code, notes, and snippets.

@kspeeckaert
Created November 15, 2021 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kspeeckaert/cf5c7be765c0fad02e1b0b9d6675aa78 to your computer and use it in GitHub Desktop.
Save kspeeckaert/cf5c7be765c0fad02e1b0b9d6675aa78 to your computer and use it in GitHub Desktop.
Send-MailMessage wrapper, with additional functionality to send attachments as an archive
function Send-CustomMail {
[cmdletbinding()]
param (
[Parameter(Mandatory)][string[]]$To,
[Parameter(Mandatory)][string]$Subject,
[Parameter(Mandatory)][string]$Body,
[string]$SMTPServer = 'SMTP.ACME.LOCAL',
[string]$From = 'support@acme.local',
[string[]]$Attachments = @(),
[Switch]$CompressAttachments
)
$Body = @"
<p><em>*** This is an automated message, do not reply! ***</em></p>
<p>$Body</p>
"@
try {
if ($Attachments.Count -gt 0) {
# Create a (local) temporary folder and copy the files to attach.
# This avoids access errors for files that are still being written to.
$TempFolder = [System.IO.Path]::Combine([System.IO.Path]::GetTempPath(),
$([System.Guid]::NewGuid()).ToString())
New-Item -ItemType Directory -Path $TempFolder | Out-Null
Write-Verbose "Copying attachments to temporary folder $TempFolder ..."
Copy-Item $Attachments -Destination $TempFolder
# Replace reference to copied files
$Attachments = Get-ChildItem $TempFolder -File | Select-Object -ExpandProperty FullName
if ($CompressAttachments) {
$Archive = [System.IO.Path]::Combine($TempFolder,
[System.IO.Path]::ChangeExtension([System.IO.Path]::GetRandomFileName(),'.zip'))
Write-Verbose "Archiving $($Attachments.Count) attachment(s)..."
try {
Compress-Archive `
-Path $Attachments `
-DestinationPath $Archive `
-CompressionLevel Optimal
# Replace the existing attachments by the archive
$Attachments = @($Archive)
}
catch {
Write-Warning "Failed to create archive, original files will be sent instead. Error: $($_.Exception.Message)"
}
}
}
$Params = @{
To = $To
From = $From
Subject = $Subject
Body = $Body
SmtpServer = $SMTPServer
Encoding = 'Unicode'
BodyAsHtml = $true
}
if ($Attachments.Count -gt 0) {
$Params['Attachments'] = $Attachments
}
Send-MailMessage @Params
}
catch {
Write-Warning "Unable to send mail. Error: $($_.Exception.Message)"
}
finally {
# Remove the temporary folder
if ($Attachments.Count -gt 0) {
Write-Verbose 'Removing temporary folder...'
Remove-Item $TempFolder -Recurse -Force -ErrorAction Ignore
}
}
}
Export-ModuleMember -Function Send-CustomMail
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment