Public/Send-Email.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<#
    .SYNOPSIS
    Sends an email using mailkit

    .DESCRIPTION
    Sends an email using mailkit

    .INPUTS
    None. You cannot pipe objects to Send-Email.

    .OUTPUTS
    None

    .PARAMETER Subject
    The subject of the email.

    .PARAMETER Message
    The message body of the email.

    .PARAMETER ToName
    The name to send the email

    .PARAMETER ToEmail
    The email address to send the email

    .EXAMPLE
    PS> Send-Email -Subject "Error has occured" -Message $ErrorMessage -ToName "Mark Lindell" -ToEmail "mark.lindell@philips.com"

    .LINK

    .NOTES
    The mailkit assemblies must be loaded or located in:
         .\MailKit.2.8.0\lib\netstandard2.0\mailkit.dll
         .\MimeKit.2.9.1\lib\netstandard2.0\MimeKit.dll
#>

function Send-Email {
    param([String]$Subject, [String]$Message, $ToName, $ToEmail)
    $config = Get-Variable -Name __emailconfig -Scope Script -ValueOnly -ErrorAction SilentlyContinue
    if (-not $config) {
        throw "Email is not configured. Use New-EamilConfig and Set-FileConfig"
    }
    if (-not ([System.Management.Automation.PSTypeName]'MailKit.Net.Smtp.SmtpClient').Type) {
        Add-Type -path ".\MailKit.2.8.0\lib\netstandard2.0\mailkit.dll"

    }
    if (-not ([System.Management.Automation.PSTypeName]'MimeKit.MimeMessage').Type) {
        Add-Type -path ".\MimeKit.2.9.1\lib\netstandard2.0\MimeKit.dll"
    }

    $smtp = New-Object MailKit.Net.Smtp.SmtpClient
    $smtp.Connect($config.Server, $config.Port)
    if ($config.credentials) {
        $smtp.Authenticate($config.credentials.GetNetworkCredential().username, $config.credentials.GetNetworkCredential().password)
    }
    $msg = New-Object MimeKit.MimeMessage
    $msg.Sender = $config.senderAddress
    $msg.Subject = $Subject
    $from = New-Object Mimekit.MailBoxAddress -ArgumentList $config.fromName, $config.fromEmail

    if ($PSBoundParameters.ContainsKey('ToName') -and $PSBoundParameters.ContainsKey('ToEmail')) {
        $to = New-Object Mimekit.MailBoxAddress -ArgumentList $ToName, $ToEmail
    } else {
        $to = New-Object Mimekit.MailBoxAddress -ArgumentList $config.toName, $config.toEmail
    }
    $body = New-Object MimeKit.TextPart -ArgumentList "plain"
    $body.Text = $Message
    $msg.From.Add($from)
    $msg.To.Add($to)
    $msg.Body = $body
    $smtp.Send($msg)
}