Search code examples
powershellpowershell-2.0powershell-3.0powershell-4.0

How to send email by using MailKit via PowerShell?


I am having difficulty creating the Message object using mailkit so I can add the From, To, Subject and body with message that may have attachments to be send before disconnecting. I have created the MailKit object, Cancelation Token object. I am able to load the MailKit and MimeKit dlls using the add-type -path and I am able to connect, authenticate, Disconnect and Dispose but the message object creation part and sending is where I need help with. I have the following:

    $MkSmtp = New-Object MailKit.Net.smtp.SmtpClient
    $CanToken = New-Object System.Threading.CancellationToken ($false)
    $SSL = [MailKit.Security.SecureSocketOptions]::SslOnConnect
    $MkSmtp.Connect($MailServer, $Port, $SSL, $CanToken)
    $MkSmtp.Authenticate(([System.Text.Encoding]::UTF8), $Username, $Password, $CanToken)

    #$Message = New-Object ????

    $MkSmtp.Send($Message)
    $MkSmtp.Disconnect($true)
    $MKSmtp.Dispose()

I thought the answer was:

    $Message = [Mimekit.MimeMessage]::new()
    $Message.From.Add($From)
    $Message.To.Add($To)
    $Message.Subject = "Test"
    $TextPart = [MimeKit.TextPart]::new("plain")
    $Body = "This is just a test"
    $TextPart.Text = $Body
    $Message.Body = $TextPart

Which came from https://www.powershellgallery.com/packages/PSGSuite/2.13.2/Content/Private%5CNew-MimeMessage.ps1. This worked on my developer machine but putting it to production yields the following error:

Method invocation failed because [MimeKit.MimeMessage] does not contain a method named 'new'

When it tries to go passed the following line:

$Message = [Mimekit.MimeMessage]::new()

Placing a breakpoint at this line after loading the dll via add-type and running "[MimeKit.MimeMessage] | Get-Member -Static" on the powershell command line on the development and production server it shows the following:

Development Development machine showing the New Static Method

Production Production server showing no New Static Method

Same DLL is loaded on both the Development and Production. I have loaded the DLL using both Add-Type and System.Reflection.Assembly. Production is on PowerShell 4.0 while my development box is on PowerShell 5.1. Don't know if that is the issue. Anyone have any ideas?


Solution

  • Updated our live server to WIndows Management Framework 5.1 (PowerShell) and now has the New Method when viewing the Static Get-Member.