handlers/mail.psm1
<#
.Synopsis Handler for mail .DESCRIPTION by default Keep=$true, this means that the mail is send only when Flush() occurs #> function New-uLogMail { param( [string] $Name, [string] $Source = $MyInvocation.ScriptName, [string] $Formatter = [LogFormatter]::MailDefault, [LogLevel] $Level = [LogLevel]::SUCCESS, [Parameter(Mandatory=$true)] [string] $From = '', [Parameter(Mandatory=$true)] [string] $To = '', [string] $Cc = '', [string] $Bcc = '', [Parameter(Mandatory=$true)] [string] $Smtp = '', [string] $Port = 25, [PSCredential] $Credentials = $null, [switch] $Append, [switch] $Keep = $true, [Switch] $Enabled = $true ) Begin{ } Process{ $log = [PSCustomObject] @{Name = $Name; Enabled = $Enabled; Type = 'mail'; Formatter = $Formatter; Level = $Level; From = $From; To = $To; Cc = $Cc; Bcc = $Bcc; Smtp = $Smtp; Port = $Port; Credentials = $Credentials; Source = $Source; Path = $Path; Data = @(); Keep = $Keep; } $log | Add-Member -MemberType ScriptMethod -Name Flush -Value { $newData = "<br><table><tr><td>" + [string]::Join("</td></tr><tr><td>", $this.Data.Message) + "</tr></td></table>" $maxLevel = ($this.Data.Level | Get-Unique | % {[LogLevel]::$_.Value__} | Measure-Object -Maximum).Maximum $level = [loglevel]::GetName([loglevel], [int] $maxLevel) if ($this.Formatter -notmatch '-'){$this.Formatter = 'Format-' + $this.Formatter} $FormattedMessage = & $this.Formatter -Record (New-LogRecord -Message $newData -Level $level ) $FormattedMessage += ("<BR><BR><b><i>Source : </b>{0}</i><BR>" -f $this.Source) #TOFIX:add Source when calling formatter #TOFIX:$newData should be an array, and formatter format the array $subject = "[{0}] - {1}" -f $level, $this.Source.Substring( $this.Source.LastIndexOf('\') + 1) $args = @{} if ($this.Cc -ne ''){$args['Cc'] = $this.Cc} if ($this.Bcc -ne ''){$args['Bcc'] = $this.Bcc} if ($this.Credentials -ne $null){$args['Credentials'] = $this.Credentials} Send-MailMessage -From $this.From ` -To $this.To ` -Smtp $this.Smtp ` -Port $this.Port ` -Subject $subject ` -BodyAsHtml $FormattedMessage ` @args $this.Data = '' } $log | Add-Member -MemberType ScriptMethod -Name WriteLog -Value { param($Record) if (-not $this.Enabled){return} if ($Record.Level -ge $this.Level){ if ($this.Keep -eq $true){ $this.Data += $Record }else{ if ($this.Formatter -notmatch '-'){$this.Formatter = 'Format-' + $this.Formatter} $FormattedMessage = & $this.Formatter -Record $Record $FormattedMessage += ("<BR><BR><BR><b><i>Source : </b>{0}</i><BR>" -f $this.Source) $subject = "[{0}] - {1}" -f $Record.Level, $this.Source.Substring( $this.Source.LastIndexOf('\') + 1) $args = @{} if ($this.Cc -ne ''){$args['Cc'] = $this.Cc} if ($this.Bcc -ne ''){$args['Bcc'] = $this.Bcc} if ($this.Credentials -ne $null){$args['Credentials'] = $this.Credentials} Send-MailMessage -From $this.From ` -To $this.To ` -Smtp $this.Smtp ` -Port $this.Port ` -Subject $subject ` -BodyAsHtml $FormattedMessage ` @args } } } $log } } |