From 68d81a8bc55ddb2c051d9a467ef29264ced09f24 Mon Sep 17 00:00:00 2001 From: The PowerShell Bear Date: Sun, 20 Mar 2022 15:31:23 -0700 Subject: [PATCH] Add support for $PSEmailServer --- PoshMailKit/SendMKMailMessage.cs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/PoshMailKit/SendMKMailMessage.cs b/PoshMailKit/SendMKMailMessage.cs index 0c1fb10..709d238 100644 --- a/PoshMailKit/SendMKMailMessage.cs +++ b/PoshMailKit/SendMKMailMessage.cs @@ -7,6 +7,7 @@ using MailKit; using MailKit.Security; using System.Net; +using System; namespace PoshMailKit { @@ -76,11 +77,9 @@ public string[] [Alias("ComputerName")] [Parameter( ParameterSetName = "Modern", - Mandatory = true, Position = 3)] [Parameter( ParameterSetName = "Legacy", - Mandatory = true, Position = 3)] public string SmtpServer { get; set; } @@ -181,7 +180,7 @@ public SwitchParameter protected override void BeginProcessing() { - ProcessParameterSets(); + ProcessParameters(); ProcessAttachments(); } @@ -216,8 +215,19 @@ protected override void ProcessRecord() processor.SendMailMessage(); } - private void ProcessParameterSets() + private void ProcessParameters() { + if (string.IsNullOrEmpty(SmtpServer)) + SmtpServer = (string)SessionState.PSVariable.Get("PSEmailServer").Value; + if (string.IsNullOrEmpty(SmtpServer)) + { + string errorMessage = "The email cannot be sent because no SMTP server was specified. " + + "You must specify an SMTP server by using either the SmtpServer parameter or the $PSEmailServer variable."; + InvalidOperationException exception = new InvalidOperationException(errorMessage); + ErrorRecord errorRecord = new ErrorRecord(exception, "", ErrorCategory.InvalidArgument, null); + ThrowTerminatingError(errorRecord); + } + if (ParameterSetName == "Legacy") { SetLegacySsl();