简体   繁体   中英

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显示新静态方法的开发机器

Production生产服务器显示没有新的静态方法

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?

将我们的实时服务器更新到 WINdows Management Framework 5.1 (PowerShell),现在在查看静态 Get-Member 时具有新方法。

$Message = New-Object Mimekit.MimeMessage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM