I have this powershell script to sending emails with attachments, but when I add multiple recipients, only the first one gets the message. I\'ve read the documentation and s
Just creating a Powershell array will do the trick
$recipients = @("Marcel <marcel@turie.eu>", "Marcelt <marcel@nbs.sk>")
The same approach can be used for attachments
$attachments = @("$PSScriptRoot\image003.png", "$PSScriptRoot\image004.jpg")
$recipients = "Marcel <marcel@turie.eu>, Marcelt <marcel@nbs.sk>"
is type of string
you need pass to send-mailmessage
a string[]
type (an array):
[string[]]$recipients = "Marcel <marcel@turie.eu>", "Marcelt <marcel@nbs.sk>"
I think that not casting to string[] do the job for the coercing rules of powershell:
$recipients = "Marcel <marcel@turie.eu>", "Marcelt <marcel@nbs.sk>"
is object[]
type but can do the same job.
You must first convert the string to a string array, like this:
$recipients = "Marcel <marcel@turie.eu>,Marcelt <marcel@nbs.sk>"
[string[]]$To = $recipients.Split(',')
Then use Send-MailMessage
like this:
Send-MailMessage -From "primasfrb@nbs.sk" -To $To -subject "New files" -body "$teloadmin" -BodyAsHtml -priority High -dno onSuccess, onFailure -smtpServer 192.168.170.61
for best behaviour create a class with a method like this
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddCommand("Send-MailMessage")
.AddParameter("SMTPServer", "smtp.xxx.com")
.AddParameter("From", "xxx@xxx.com")
.AddParameter("Subject", "xxx Notification")
.AddParameter("Body", body_msg)
.AddParameter("BodyAsHtml")
.AddParameter("To", recipients);
// invoke execution on the pipeline (ignore output) --> nothing will be displayed
PowerShellInstance.Invoke();
}
Whereby these instance is called in a function like:
public void sendEMailPowerShell(string body_msg, string[] recipients)
Never forget to use a string array for the recepients, which can be look like this:
string[] reportRecipient = {
"xxx <xxx.Fercher@xxx.com>",
"xxx <xxx@xxx.com>"
};
this message can be overgiven as parameter to the method itself, HTML coding enabled!!
never forget to use a string array in case of multiple recipients, otherwise only the last address in the string will be used!!!
mail reportMail = new mail(); //instantiate from class
reportMail.sendEMailPowerShell(reportMessage, reportRecipient); //msg + email addresses
To define an array of strings it is more comfortable to use $var = @('User1 ', 'User2 ').
$servername = hostname
$smtpserver = 'localhost'
$emailTo = @('username1 <user1@dom.com>', 'username2<user2@dom.com>')
$emailFrom = 'SomeServer <user3@dom.com>'
Send-MailMessage -To $emailTo -Subject 'Low available memory' -Body 'Warning' -SmtpServer $smtpserver -From $emailFrom
That's right, each address needs to be quoted. If you have multiple addresses listed on the command line, the Send-MailMessage likes it if you specify both the human friendly and the email address parts.