So we've all used the send-mailmessage command in PowerShell to email things around. But what do you do when you have to send an email to multiple recipients?
Turns out the answer is easy but there's a bit of a twist that I never thought about until someone asked me "Why do I get an error when I use more than one recipient with the send-mailmessage command?"
I looked at their command and the answer was obvious to me but not so much to them. They were using the following:
PS C:\> $to="me@fabrikam.com,me2@fabrikam.com"
PS C:\> $body="This is my test mail"
PS C:\> Send-MailMessage -From "me@contoso.com" -To $to -Subject "Testing" -Body $body -BodyAsHtml -SmtpServer 10.10.10.10
When you run the command you get:
Send-MailMessage : An invalid character was found in the mail header: ','.
At line:1 char:1
+ Send-MailMessage -From "me@contoso.com" -To $to -Subject "Testing" -Body $body - ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidType: (:) [Send-MailMessage], FormatException
+ FullyQualifiedErrorId : FormatException,Microsoft.PowerShell.Commands.SendMailMessage
Send-MailMessage : A recipient must be specified.
At line:1 char:1
+ Send-MailMessage -From "me@contoso.com" -To $to -Subject "Testing" -Body $body - ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], InvalidOpe
rationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.SendMailMessage
So it's complaining that you didn't give it a recipient?!? But you did, you told it to use the $to variable. Trouble is that the variable isn't the right type. If you look at the command's doc (Send-MailMessage) you'll see that it wants a type of string[] (this is an array of strings).
So what is our variable? Lets look using the gettype():
PS C:\> $to.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
So our variable is a String, not a String[]. Doesn't seem like much of a difference but it is. The trick is to quote each comma separated value so that the variable is in a format that the command can use.
Here's the correct format:
PS C:\> $to="me@fabrikam.com","me2@fabrikam.com"
Which is technically not string[] but functionally is the same thing as it's an array of strings.
PS C:\> $to.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
So there you have it a simple change in the variable makes a big difference. now you can send your report to multiple people without having to (as this person was doing) make a DL containing all the recipients.