From Microsoft documentation.
Send-MailMessage
-To
The To parameter is required. This parameter specifies the
recipient's email address. If there are multiple recipients, separate
their addresses with a comma (,). Enter names (optional) and the email
address, such as Name someone@fabrikam.com.
Let's highlight the important parts of your code here:
#...
$To = (Select-String -Path $Content -Pattern "To:(.*)").Matches.Groups[1].Value
#...
Send-MailMessage -From $From -To $To -Cc $Cc -SmtpServer $SMTPServer -Subject $Subject -Body $Body
Now consider the following
$To
$To.GetType()
The result will be
user2@example.com, user3@example.com
String
This is your problem.
If you want to send to multiple recipients, you need to pass an array of string.
That being said, you are passing a single string (and so a single email, code-wise) with the value user2@example.com, user3@example.com
.
To correct your issue, add .Split(',') | % {$_.Trim()}
to your $To
line.
$To = (Select-String -Path $Content -Pattern "To:(.*)").Matches.Groups[1].Value.Split(',') | % {$_.Trim()}
The .Split(',')
will convert the string into an array, using the comma as delimiter and the | % {$_.Trim()}
will trim the empty spaces before and after each email addresses, if any.
Now, if you try $To.GetType()
, you will get a System.Array
of Object[]
.
Your Send-MailMessage
should work properly after that (if there is no other errors preventing it from working)
Additional Note:
Your $CC
and $BCC
(should you add one) will need the same .Split(',')
treatment to convert them from String to array so that they are viewed as multiple email addresses by the Send-MailMessage
cmdlet.
Regarding the body, you can use something like this to get the remaining lines...
$Body = ((Select-String -Path $Content -Pattern "Body:(.*)" -Context 0, 100)| ForEach-Object {
(, $_.Line + $_.Context.PostContext)
}) -join [System.Environment]::NewLine
$Body = ($Body -Replace 'patchname', $patchName).Substring(5).Trim()
Note that your replace won't do anything with the current message since "patchname" is not part of the template.
References
MS doc - Send-MailMessage
SO - How to Select-String multiline?