Plugins/Mail.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# Author: Miodrag Milic <miodrag.milic@gmail.com>
# Last Change: 24-Sep-2016.

param(
    $Info,
    [string]   $To,
    [string]   $Server,
    [string]   $UserName,
    [string]   $Password,
    [int]      $Port,
    [string[]] $Attachment,
    [switch]   $EnableSsl,
    [string]   $UserMessage,
    # Do not send only on errors
    [switch]   $SendAlways
)

if (($Info.error_count.total -eq 0) -and !$SendAlways) {
    Write-Host 'Mail not sent as there are no errors (override with SendAlways param)'
    return
}

$errors_word = if ($Info.error_count.total -eq 1) {'error'} else {'errors' }

# Create mail message
$from = "Update-AUPackages@{0}.{1}" -f $Env:UserName, $Env:ComputerName

$msg = New-Object System.Net.Mail.MailMessage $from, $To
$msg.IsBodyHTML = $true

if ($Info.error_count.total -eq 0) {
    $msg.Subject = "AU: run was OK"
    $msg.Body = $Info.stats | Out-String
}
else {
    $context = "with errors "
    $msg.Subject    = "AU: $($info.error_count.total) $errors_word during update"
    $msg.Body = @"
<body><pre>
$($Info.error_count.total) $errors_word during update.
$UserMessage
$($info.error_info | Out-String)
</pre></body>
"@

}

$Attachment | % { if ($_) { $msg.Attachments.Add($_)} }

# Send mail message
$smtp = new-object Net.Mail.SmtpClient($Server)
if ($UserName) { $smtp.Credentials = new-object System.Net.NetworkCredential($UserName, $Password) }
if ($Port)     { $smtp.Port = $Port }
$smtp.EnableSsl = $EnableSsl
$smtp.Send($msg)

Write-Host "Mail ${context}sent to $To"