Script runs in VS Code but not Powershell

114 Views Asked by At

I am trying to use MailKit/MimeKit to send emails through Powershell. I have a simple script that sends emails successfully when I run it from VS Code, but the same script does not work from Powershell. Interestingly, one of the errors I get from Powershell also comes up on VS Code, but the emails still send.

Here's the part of the code that sends the email:

function sendEmail($to, $subject, $content){

Add-Type -Path "C:\ProgramFiles\PackageManagement\NuGet\Packages\MailKit.4.0.0\lib\netstandard2.0\MailKit.dll"
  
Add-Type -Path "C:\ProgramFiles\PackageManagement\NuGet\Packages\MimeKit.4.0.0\lib\netstandard2.0\MimeKit.dll"
    
    $SMTP     = New-Object MailKit.Net.Smtp.SmtpClient
    $Message  = New-Object MimeKit.MimeMessage
    $TextPart = [MimeKit.TextPart]::new("plain")
    $TextPart.Text = $content
    $Message.From.Add("[email protected]")

    #add each recipient email
    foreach($email in $to){
        $Message.To.Add($email)
    }
    $Message.Subject = $subject
    $Message.Body    = $TextPart
    $SMTP.Connect('smtp.gmail.com', 587, $False)

    #app specific password needed to access gmail
    $SMTP.Authenticate('[email protected]', 'password' )
    $SMTP.Send($Message)
    $SMTP.Disconnect($true)
    $SMTP.Dispose()

}

These are the first couple error messages I get for MimeKit and MailKit from Powershell. I get the same error only for MimeKit from VS Code, but it still sends the emails:

Add-Type : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
At C:\Users\Me\Documents\Scripts\Email\testing-email.ps1:5 char:5

  • Add-Type -Path "C:\Program Files\PackageManagement\NuGet\Packages ...
    
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : NotSpecified: (:) [Add-Type], ReflectionTypeLoadException
    • FullyQualifiedErrorId : System.Reflection.ReflectionTypeLoadException,Microsoft.PowerShell.Commands.AddTypeCommand
1

There are 1 best solutions below

0
jstedfast On

You need PowerShell 7.1 because you are loading the netstandard2.0 versions of MimeKit and MailKit assemblies. PowerShell 5.1 can only load .NETFramework assemblies as far as I'm aware.

You could try loading the .NETFramework versions of MimeKit and MailKit to see if that works, but it might not because they depend on some System.* nugets as well.

C:\ProgramFiles\PackageManagement\NuGet\Packages\MimeKit.4.0.0\lib\net462\MimeKit.dll C:\ProgramFiles\PackageManagement\NuGet\Packages\MailKit.4.0.0\lib\net462\MailKit.dll

It should also be noted that MailKit depends on MimeKit, so MimeKit should be loaded first.