Public/Send-Email.ps1

<#
    .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)
}