Skip to content

Update MailKit step template to version 2 - #1720

Merged
harrisonmeister merged 1 commit into
masterfrom
mh/send-mail-mailkit-fix
Nov 30, 2026
Merged

harrisonmeister merged 1 commit into
masterfrom
mh/send-mail-mailkit-fix

Conversation

@harrisonmeister

Copy link
Copy Markdown
Contributor

Background

MimeKit and MailKit 5.0.0 broke the Send Email using MailKit step in three ways:

  1. MimeKit is now a meta-package with no assemblies. The library code moved to MimeKit.Core (and MimeKit.Cryptography), so the hardcoded path lib/netstandard2.1/MimeKit.dll no longer exists and Add-Type fails.
  2. The step hardcoded the netstandard2.1 target folder, which isn't guaranteed to exist in every package version.
  3. SmtpClient.Send(MimeMessage) was removed. MailKit 5 expects Send(ISendRequest, CancellationToken) and returns a SendResult.

The step also picked up whatever version of each package was installed first, so a worker could end up loading MimeKit 4.x alongside MailKit 5.x.

Results

  • Installs and loads MimeKit.Core and MailKit instead of the MimeKit meta-package.
  • Pins both packages to the same version (default 5.0.0). A new optional parameter, SendEmail.MailKitVersion, overrides it.
  • Picks the best lib folder for the PowerShell runtime (netX.0 up to the runtime version, then netstandard2.1, then netstandard2.0) instead of hardcoding one. If nothing fits, the error lists the folders that do exist.
  • Get-Package now filters by -ProviderName NuGet and -RequiredVersion, so stale or unrelated packages on the worker aren't used.
  • Sends with [MailKit.SendRequest]::new($Message), logs the server response at verbose level and warns about rejected recipients.
  • Trims whitespace from comma-separated TO and CC addresses.
  • Disposes the SMTP client in a finally block so it's cleaned up when sending fails.
  • Version bumped from 1 to 2. Description updated to mention MimeKit.Core.

Before

Loading MimeKit:

Cannot find path '/home/tentacle/.local/share/PackageManagement/NuGet/Packages/MimeKit.5.0.0/lib/netstandard2.1/MimeKit.dll' because it does not exist.
At Script.ps1:56 char:16
+ Add-Type -Path $MimeKitPath

Sending (after working around the load failure):

Cannot find an overload for "Send" and the argument count: "1".
At Script.ps1:162 char:5
+     $SMTP.Send($Message)

After

Sending email... 
Email sent. 

Pre-requisites

  • Id should be a GUID that is not 00000000-0000-0000-0000-000000000000
    • NOTE If you are modifying an existing step template, please make sure that you do not modify the Id property (updating the Id will break the Library sync functionality in Octopus).
  • Version should be incremented, otherwise the integration with Octopus won't update the step template correctly
  • $Meta must have ExportedAt and OctopusVersion updated
  • Parameter names should not start with $
  • Step template parameter names (the ones declared in the JSON, not the script body) should be prefixed with a namespace so that they are less likely to clash with other user-defined variables in Octopus (see this issue). For example, use an abbreviated name of the step template or the category of the step template).
  • LastModifiedBy field must be present, and (optionally) updated with the correct author
  • The best practices documented here have been applied

Updated the MailKit step template to version 2, modifying the required packages to include MimeKit.Core instead of MimeKit. Adjusted the script body for compatibility with the new package structure and improved parameter handling.
@github-actions

Copy link
Copy Markdown

Review this PR in Hyponome for a side-by-side diff of the step-template JSON and any embedded scripts.

@mcasperson
mcasperson requested review from mcasperson and a balanced review from Copilot November 30, 2026 07:54

@mcasperson mcasperson left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The rejected-recipient warning is unreachable because MailKit throws before returning a result, and reusing a mismatched loaded assembly can fail when the required SendRequest type is unavailable.

2 open issues
What changed in this PR

Updates the library’s Send Email using MailKit step template to version 2, targeting MailKit 5 compatibility on PowerShell Core workers.

Changes:

  • Switches to MimeKit.Core, pins package versions with an optional override, and selects runtime-compatible assemblies.
  • Adopts the new send API, adds response logging, trims recipient addresses, and ensures SMTP client disposal.
  • Updates the template description and export metadata.
File Description
step-templates/​send-email-using-mailkit.json Updates package loading, email sending, parameters, and metadata for template version 2.

Review effort: Balanced

"Octopus.Action.EnabledFeatures": "Octopus.Features.SelectPowerShellEditionForWindows",
"Octopus.Action.Script.ScriptSource": "Inline",
"Octopus.Action.Script.Syntax": "PowerShell",
"Octopus.Action.Script.ScriptBody": "$ErrorActionPreference = \"Stop\";\n\nif ($PSEdition -eq \"Core\") {\n $PSStyle.OutputRendering = \"PlainText\"\n}\n$emailSubject = $OctopusParameters[\"SendEmail.Subject\"]\n$emailSmtpServer = $OctopusParameters[\"SendEmail.SmtpServer\"]\n$emailSmtpPort = $OctopusParameters[\"SendEmail.SmtpPort\"]\n$emailCredentialsUsername = $OctopusParameters[\"SendEmail.Credentials.Username\"]\n$emailCredentialsPassword = $OctopusParameters[\"SendEmail.Credentials.Password\"]\n$emailSecureSocketOption = $OctopusParameters[\"SendEmail.SecureSocketOption\"]\n\n$validSecureSocketOptions = @(\"None\", \"Auto\", \"SslOnConnect\", \"StartTls\", \"StartTlsWhenAvailable\")\nif(-not $validSecureSocketOptions.Contains($emailSecureSocketOption)) {\n Write-Error \"Invalid SecureSocketOption: $emailSecureSocketOption. Must be one of: $($validSecureSocketOptions -join \", \").\"\n return\n}\n\n$emailFromAddress = $OctopusParameters[\"SendEmail.FromAddress\"]\n$emailToAddresses = $OctopusParameters[\"SendEmail.TOAddresses\"]\n$emailCcAddresses = $OctopusParameters[\"SendEmail.CCAddresses\"]\n$emailReplyToAddress = $OctopusParameters[\"SendEmail.ReplyToAddress\"]\n\n$HtmlBody = $OctopusParameters[\"SendEmail.HtmlBody\"]\n$TextBody = $OctopusParameters[\"SendEmail.TextBody\"]\n\n# MimeKit 5 split into packages: \"MimeKit\" is now a meta-package with no DLLs.\n# The core library is in MimeKit.Core. MimeKit.Core and MailKit are pinned to the\n# same version so they always match. Override with SendEmail.MailKitVersion if set.\n$mailKitVersion = $OctopusParameters[\"SendEmail.MailKitVersion\"]\nif ([string]::IsNullOrWhiteSpace($mailKitVersion)) {\n $mailKitVersion = \"5.0.0\"\n}\n\n# Load order matters: MimeKit.Core first, then MailKit.\n$requiredPackages = @(\"MimeKit.Core\", \"MailKit\")\n\nfunction Get-BestLibDir {\n param($Package)\n\n if (-not $Package -or -not $Package.Source) {\n throw \"Package object is null or has no Source. Did Install-Package/Get-Package succeed?\"\n }\n\n $packageDir = Split-Path $Package.Source -Parent\n $root = Join-Path $packageDir \"lib\"\n if (-not (Test-Path $root)) {\n $contents = (Get-ChildItem -Path $packageDir).Name -join \", \"\n throw \"No lib folder for $($Package.Name) $($Package.Version). Package contains: $contents\"\n }\n\n $runtimeMajor = [Environment]::Version.Major\n\n $best = Get-ChildItem -Path $root -Directory | ForEach-Object {\n $name = $_.Name\n $rank = if ($name -match '^net(\\d+)\\.\\d+$' -and [int]$Matches[1] -le $runtimeMajor) { 1000 + [int]$Matches[1] }\n elseif ($name -eq \"netstandard2.1\") { 500 }\n elseif ($name -eq \"netstandard2.0\") { 400 }\n else { -1 } # skips net462/net47/net48 and builds newer than the runtime\n [pscustomobject]@{ Dir = $_.FullName; Rank = $rank }\n } | Where-Object { $_.Rank -ge 0 -and (Get-ChildItem -Path $_.Dir -Filter *.dll) } |\n Sort-Object Rank -Descending | Select-Object -First 1\n\n if (-not $best) {\n $available = (Get-ChildItem -Path $root -Directory).Name -join \", \"\n throw \"No compatible build of $($Package.Name) under $root for .NET $runtimeMajor. Available: $available\"\n }\n $best.Dir\n}\n\nWrite-Verbose \"Runtime: .NET $([Environment]::Version)\"\nWrite-Verbose \"Checking for MimeKit.Core and MailKit $mailKitVersion packages.\"\n\nforeach ($packageName in $requiredPackages) {\n $package = Get-Package -Name $packageName -ProviderName NuGet -RequiredVersion $mailKitVersion -ErrorAction SilentlyContinue |\n Select-Object -First 1\n\n if ($null -eq $package) {\n Write-Output \"Downloading $packageName $mailKitVersion from nuget.org.\"\n Install-Package -Name $packageName -RequiredVersion $mailKitVersion -Source \"https://www.nuget.org/api/v2\" -SkipDependencies -Force -Scope CurrentUser | Out-Null\n $package = Get-Package -Name $packageName -ProviderName NuGet -RequiredVersion $mailKitVersion | Select-Object -First 1\n }\n\n $libDir = Get-BestLibDir -Package $package\n\n foreach ($dll in Get-ChildItem -Path $libDir -Filter *.dll) {\n $asmName = [System.Reflection.AssemblyName]::GetAssemblyName($dll.FullName)\n $loaded = [AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq $asmName.Name } | Select-Object -First 1\n\n if ($loaded) {\n if ($loaded.GetName().Version -ne $asmName.Version) {\n Write-Warning \"$($asmName.Name) $($loaded.GetName().Version) is already loaded in this session; expected $($asmName.Version).\"\n }\n continue\n }\n\n Write-Verbose \"Loading $($asmName.Name) $($asmName.Version) from $($dll.FullName)\"\n Add-Type -Path $dll.FullName\n }\n}\n\n# Validation/Setting of Secure Socket Options needed after libraries loaded\nswitch($emailSecureSocketOption) {\n \"Auto\" {\n $secureSocketOption = [MailKit.Security.SecureSocketOptions]::Auto\n }\n \"None\" {\n $secureSocketOption = [MailKit.Security.SecureSocketOptions]::None\n }\n \"SslOnConnect\" {\n $secureSocketOption = [MailKit.Security.SecureSocketOptions]::SslOnConnect\n }\n \"StartTls\" {\n $secureSocketOption = [MailKit.Security.SecureSocketOptions]::StartTls\n }\n \"StartTlsWhenAvailable\" {\n $secureSocketOption = [MailKit.Security.SecureSocketOptions]::StartTlsWhenAvailable\n }\n default {\n Write-Error \"Invalid SecureSocketOption: $emailSecureSocketOption. Must be one of: $($validSecureSocketOptions -join \", \").\"\n return\n }\n}\n\n$SMTP = New-Object MailKit.Net.Smtp.SmtpClient\n\ntry {\n $Message = New-Object MimeKit.MimeMessage\n $ContentBuilder = [MimeKit.BodyBuilder]::new()\n\n $ContentBuilder.HtmlBody = $HtmlBody\n $ContentBuilder.TextBody = $TextBody\n Write-Verbose \"Setting From address: $emailFromAddress\"\n $Message.From.Add($emailFromAddress)\n $toAddresses = $emailToAddresses -split \",\"\n Write-Verbose \"Setting TO addresses: $emailToAddresses\"\n foreach($toAddress in $toAddresses) {\n $Message.To.Add($toAddress.Trim())\n }\n\n if(-not [string]::IsNullOrWhitespace($emailCcAddresses)) {\n Write-Verbose \"Setting CC addresses: $emailCcAddresses\"\n $ccAddresses = $emailCcAddresses -split \",\"\n foreach($ccAddress in $ccAddresses) {\n $Message.Cc.Add($ccAddress.Trim())\n }\n }\n if(-not [string]::IsNullOrWhitespace($emailReplyToAddress)) {\n Write-Verbose \"Setting ReplyTo address: $emailReplyToAddress\"\n $Message.ReplyTo.Add($emailReplyToAddress)\n }\n\n Write-Verbose \"Setting subject to: $emailSubject\"\n $Message.Subject = $emailSubject\n Write-Verbose \"Setting MimeMessage Body contents\"\n $Message.Body = $ContentBuilder.ToMessageBody()\n Write-Verbose \"Connecting to SMTP server: $emailSmtpServer on port: $emailSmtpPort (using SecureSocketOption=$emailSecureSocketOption)\"\n $SMTP.Connect($emailSmtpServer, $emailSmtpPort, $secureSocketOption)\n Write-Verbose \"Authenticating...\"\n $SMTP.Authenticate($emailCredentialsUsername, $emailCredentialsPassword)\n Write-Output \"Sending email...\"\n # MailKit 5 replaced Send(MimeMessage) with Send(ISendRequest). Wrap the message in a\n # SendRequest and pass the CancellationToken explicitly so PowerShell resolves the overload.\n $sendRequest = [MailKit.SendRequest]::new($Message)\n $sendResult = $SMTP.Send($sendRequest, [System.Threading.CancellationToken]::None)\n Write-Verbose \"Server response: $($sendResult.ResponseText)\"\n if ($sendResult.RejectedRecipients.Count -gt 0) {\n Write-Warning \"Rejected recipients: $($sendResult.RejectedRecipients -join \", \")\"\n }\n Write-Output \"Email sent.\"\n $SMTP.Disconnect($true)\n}\nfinally {\n $SMTP.Dispose()\n}"
"Octopus.Action.EnabledFeatures": "Octopus.Features.SelectPowerShellEditionForWindows",
"Octopus.Action.Script.ScriptSource": "Inline",
"Octopus.Action.Script.Syntax": "PowerShell",
"Octopus.Action.Script.ScriptBody": "$ErrorActionPreference = \"Stop\";\n\nif ($PSEdition -eq \"Core\") {\n $PSStyle.OutputRendering = \"PlainText\"\n}\n$emailSubject = $OctopusParameters[\"SendEmail.Subject\"]\n$emailSmtpServer = $OctopusParameters[\"SendEmail.SmtpServer\"]\n$emailSmtpPort = $OctopusParameters[\"SendEmail.SmtpPort\"]\n$emailCredentialsUsername = $OctopusParameters[\"SendEmail.Credentials.Username\"]\n$emailCredentialsPassword = $OctopusParameters[\"SendEmail.Credentials.Password\"]\n$emailSecureSocketOption = $OctopusParameters[\"SendEmail.SecureSocketOption\"]\n\n$validSecureSocketOptions = @(\"None\", \"Auto\", \"SslOnConnect\", \"StartTls\", \"StartTlsWhenAvailable\")\nif(-not $validSecureSocketOptions.Contains($emailSecureSocketOption)) {\n Write-Error \"Invalid SecureSocketOption: $emailSecureSocketOption. Must be one of: $($validSecureSocketOptions -join \", \").\"\n return\n}\n\n$emailFromAddress = $OctopusParameters[\"SendEmail.FromAddress\"]\n$emailToAddresses = $OctopusParameters[\"SendEmail.TOAddresses\"]\n$emailCcAddresses = $OctopusParameters[\"SendEmail.CCAddresses\"]\n$emailReplyToAddress = $OctopusParameters[\"SendEmail.ReplyToAddress\"]\n\n$HtmlBody = $OctopusParameters[\"SendEmail.HtmlBody\"]\n$TextBody = $OctopusParameters[\"SendEmail.TextBody\"]\n\n# MimeKit 5 split into packages: \"MimeKit\" is now a meta-package with no DLLs.\n# The core library is in MimeKit.Core. MimeKit.Core and MailKit are pinned to the\n# same version so they always match. Override with SendEmail.MailKitVersion if set.\n$mailKitVersion = $OctopusParameters[\"SendEmail.MailKitVersion\"]\nif ([string]::IsNullOrWhiteSpace($mailKitVersion)) {\n $mailKitVersion = \"5.0.0\"\n}\n\n# Load order matters: MimeKit.Core first, then MailKit.\n$requiredPackages = @(\"MimeKit.Core\", \"MailKit\")\n\nfunction Get-BestLibDir {\n param($Package)\n\n if (-not $Package -or -not $Package.Source) {\n throw \"Package object is null or has no Source. Did Install-Package/Get-Package succeed?\"\n }\n\n $packageDir = Split-Path $Package.Source -Parent\n $root = Join-Path $packageDir \"lib\"\n if (-not (Test-Path $root)) {\n $contents = (Get-ChildItem -Path $packageDir).Name -join \", \"\n throw \"No lib folder for $($Package.Name) $($Package.Version). Package contains: $contents\"\n }\n\n $runtimeMajor = [Environment]::Version.Major\n\n $best = Get-ChildItem -Path $root -Directory | ForEach-Object {\n $name = $_.Name\n $rank = if ($name -match '^net(\\d+)\\.\\d+$' -and [int]$Matches[1] -le $runtimeMajor) { 1000 + [int]$Matches[1] }\n elseif ($name -eq \"netstandard2.1\") { 500 }\n elseif ($name -eq \"netstandard2.0\") { 400 }\n else { -1 } # skips net462/net47/net48 and builds newer than the runtime\n [pscustomobject]@{ Dir = $_.FullName; Rank = $rank }\n } | Where-Object { $_.Rank -ge 0 -and (Get-ChildItem -Path $_.Dir -Filter *.dll) } |\n Sort-Object Rank -Descending | Select-Object -First 1\n\n if (-not $best) {\n $available = (Get-ChildItem -Path $root -Directory).Name -join \", \"\n throw \"No compatible build of $($Package.Name) under $root for .NET $runtimeMajor. Available: $available\"\n }\n $best.Dir\n}\n\nWrite-Verbose \"Runtime: .NET $([Environment]::Version)\"\nWrite-Verbose \"Checking for MimeKit.Core and MailKit $mailKitVersion packages.\"\n\nforeach ($packageName in $requiredPackages) {\n $package = Get-Package -Name $packageName -ProviderName NuGet -RequiredVersion $mailKitVersion -ErrorAction SilentlyContinue |\n Select-Object -First 1\n\n if ($null -eq $package) {\n Write-Output \"Downloading $packageName $mailKitVersion from nuget.org.\"\n Install-Package -Name $packageName -RequiredVersion $mailKitVersion -Source \"https://www.nuget.org/api/v2\" -SkipDependencies -Force -Scope CurrentUser | Out-Null\n $package = Get-Package -Name $packageName -ProviderName NuGet -RequiredVersion $mailKitVersion | Select-Object -First 1\n }\n\n $libDir = Get-BestLibDir -Package $package\n\n foreach ($dll in Get-ChildItem -Path $libDir -Filter *.dll) {\n $asmName = [System.Reflection.AssemblyName]::GetAssemblyName($dll.FullName)\n $loaded = [AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetName().Name -eq $asmName.Name } | Select-Object -First 1\n\n if ($loaded) {\n if ($loaded.GetName().Version -ne $asmName.Version) {\n Write-Warning \"$($asmName.Name) $($loaded.GetName().Version) is already loaded in this session; expected $($asmName.Version).\"\n }\n continue\n }\n\n Write-Verbose \"Loading $($asmName.Name) $($asmName.Version) from $($dll.FullName)\"\n Add-Type -Path $dll.FullName\n }\n}\n\n# Validation/Setting of Secure Socket Options needed after libraries loaded\nswitch($emailSecureSocketOption) {\n \"Auto\" {\n $secureSocketOption = [MailKit.Security.SecureSocketOptions]::Auto\n }\n \"None\" {\n $secureSocketOption = [MailKit.Security.SecureSocketOptions]::None\n }\n \"SslOnConnect\" {\n $secureSocketOption = [MailKit.Security.SecureSocketOptions]::SslOnConnect\n }\n \"StartTls\" {\n $secureSocketOption = [MailKit.Security.SecureSocketOptions]::StartTls\n }\n \"StartTlsWhenAvailable\" {\n $secureSocketOption = [MailKit.Security.SecureSocketOptions]::StartTlsWhenAvailable\n }\n default {\n Write-Error \"Invalid SecureSocketOption: $emailSecureSocketOption. Must be one of: $($validSecureSocketOptions -join \", \").\"\n return\n }\n}\n\n$SMTP = New-Object MailKit.Net.Smtp.SmtpClient\n\ntry {\n $Message = New-Object MimeKit.MimeMessage\n $ContentBuilder = [MimeKit.BodyBuilder]::new()\n\n $ContentBuilder.HtmlBody = $HtmlBody\n $ContentBuilder.TextBody = $TextBody\n Write-Verbose \"Setting From address: $emailFromAddress\"\n $Message.From.Add($emailFromAddress)\n $toAddresses = $emailToAddresses -split \",\"\n Write-Verbose \"Setting TO addresses: $emailToAddresses\"\n foreach($toAddress in $toAddresses) {\n $Message.To.Add($toAddress.Trim())\n }\n\n if(-not [string]::IsNullOrWhitespace($emailCcAddresses)) {\n Write-Verbose \"Setting CC addresses: $emailCcAddresses\"\n $ccAddresses = $emailCcAddresses -split \",\"\n foreach($ccAddress in $ccAddresses) {\n $Message.Cc.Add($ccAddress.Trim())\n }\n }\n if(-not [string]::IsNullOrWhitespace($emailReplyToAddress)) {\n Write-Verbose \"Setting ReplyTo address: $emailReplyToAddress\"\n $Message.ReplyTo.Add($emailReplyToAddress)\n }\n\n Write-Verbose \"Setting subject to: $emailSubject\"\n $Message.Subject = $emailSubject\n Write-Verbose \"Setting MimeMessage Body contents\"\n $Message.Body = $ContentBuilder.ToMessageBody()\n Write-Verbose \"Connecting to SMTP server: $emailSmtpServer on port: $emailSmtpPort (using SecureSocketOption=$emailSecureSocketOption)\"\n $SMTP.Connect($emailSmtpServer, $emailSmtpPort, $secureSocketOption)\n Write-Verbose \"Authenticating...\"\n $SMTP.Authenticate($emailCredentialsUsername, $emailCredentialsPassword)\n Write-Output \"Sending email...\"\n # MailKit 5 replaced Send(MimeMessage) with Send(ISendRequest). Wrap the message in a\n # SendRequest and pass the CancellationToken explicitly so PowerShell resolves the overload.\n $sendRequest = [MailKit.SendRequest]::new($Message)\n $sendResult = $SMTP.Send($sendRequest, [System.Threading.CancellationToken]::None)\n Write-Verbose \"Server response: $($sendResult.ResponseText)\"\n if ($sendResult.RejectedRecipients.Count -gt 0) {\n Write-Warning \"Rejected recipients: $($sendResult.RejectedRecipients -join \", \")\"\n }\n Write-Output \"Email sent.\"\n $SMTP.Disconnect($true)\n}\nfinally {\n $SMTP.Dispose()\n}"
@harrisonmeister
harrisonmeister merged commit f44aac0 into master Nov 30, 2026
5 checks passed
@harrisonmeister
harrisonmeister deleted the mh/send-mail-mailkit-fix branch November 30, 2026 08:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants