首页 > 解决方案 > MailKit/MimeKit 在 PowerShell 4 上出现错误,但在 PowerShell 5.1 上有效

问题描述

当我在使用 PowerShell 4.0 但在使用 PowerShell 5.1 的开发人员机器上工作的生产服务器上尝试使用 MailKit/MimeKit 版本 2.5.1 发送电子邮件时,出现错误“参数类型不匹配”

生产和开发机器的系统信息如下: 在此处输入图像描述

在尝试运行 $MkSmtp.Send($Message) 后,我在 try/catch 中收到生产错误:

在此处输入图像描述

我的代码如下所示:

    #Load the .NET Core class dll for Mailkit based on .NET 4.5
    add-type -path "c:\Windows\System32\WindowsPowerShell\v1.0\Modules\EmailUtilities\MailKit.dll"
    add-type -path "c:\Windows\System32\WindowsPowerShell\v1.0\Modules\EmailUtilities\MimeKit.dll"

    #Server and Mailbox properties for less secure access when connecting to google
    $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)
    #have the building of the message in a separate function which also worked
    #on development PowerShell 5.1 but not on production PowerShell 4 but rebuilt message
    #here until I figure it out
    #--------------
    $Message = New-Object MimeKit.MimeMessage
    $Message.From.Add($global:EmailFrom)
    $Message.To.Add($global:EmailTo)
    $Message.Subject = "Test";
    $TextPart = New-Object MimeKit.TextPart ("plain")
    $TextPart.Text = "Testing message..."
    $Message.Body = $TextPart
    #$Options = New-Object MimeKit.Net.Smtp.FormatOptions.Default.Clone
    #$Options.International = $true

    #$Message = New-MimeMessage $global:EmailFrom $global:EmailTo $Subject $LogMsg
    $MkSmtp.Send($Message)
    $MkSmtp.Disconnect($true)
    $MkSmtp.Dispose()
    #--------------

标签: powershell-4.0

解决方案


将我们的实时服务器更新为 Windows Management Framework 5.1 (PowerShell),现在可以像我的开发机器一样按预期工作。


推荐阅读