Powershell send-mailmessage - email to multiple recipients

Powershell

Powershell Problem Overview


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 still can't figure it out. Thank you

$recipients = "Marcel <[email protected]>, Marcelt <[email protected]>"
 
Get-ChildItem "C:\Decrypted\" | Where {-NOT $_.PSIsContainer} | foreach {$_.fullname} |
send-mailmessage -from "[email protected]" `
            -to "$recipients" `
            -subject "New files" `
            -body "$teloadmin" `
            -BodyAsHtml `
            -priority  High `
            -dno onSuccess, onFailure `
            -smtpServer  192.168.170.61

Powershell Solutions


Solution 1 - Powershell

$recipients = "Marcel <[email protected]>, Marcelt <[email protected]>"

is type of string you need pass to send-mailmessage a string[] type (an array):

[string[]]$recipients = "Marcel <[email protected]>", "Marcelt <[email protected]>"

I think that not casting to string[] do the job for the coercing rules of powershell:

$recipients = "Marcel <[email protected]>", "Marcelt <[email protected]>"

is object[] type but can do the same job.

Solution 2 - Powershell

Just creating a Powershell array will do the trick

$recipients = @("Marcel <[email protected]>", "Marcelt <[email protected]>")

The same approach can be used for attachments

$attachments = @("$PSScriptRoot\image003.png", "$PSScriptRoot\image004.jpg")

Solution 3 - Powershell

You must first convert the string to a string array, like this:

$recipients = "Marcel <[email protected]>,Marcelt <[email protected]>"
[string[]]$To = $recipients.Split(',')

Then use Send-MailMessage like this:

Send-MailMessage -From "[email protected]" -To $To -subject "New files" -body "$teloadmin" -BodyAsHtml -priority High -dno onSuccess, onFailure -smtpServer 192.168.170.61

Solution 4 - Powershell

To define an array of strings it is more comfortable to use $var = @('User1 <[email protected]>', 'User2 <[email protected]>').

$servername = hostname
$smtpserver = 'localhost'
$emailTo = @('username1 <[email protected]>', 'username2<[email protected]>')
$emailFrom = 'SomeServer <[email protected]>'
Send-MailMessage -To $emailTo -Subject 'Low available memory' -Body 'Warning' -SmtpServer $smtpserver -From $emailFrom

Solution 5 - Powershell

Here is a full (Gmail) and simple solution... just use the normal ; delimiter.. best for passing in as params.

$to = "[email protected];[email protected]"
$user = "[email protected]"    
$pass = "password"

$pass = ConvertTo-SecureString -String $pass -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential $user, $pass
$mailParam = @{
    To = $to.Split(';')
    From = "IT Alerts <[email protected]>"
    Subject = "test"
    Body = "test"
    SmtpServer = "smtp.gmail.com"
    Port = 587 #465
    Credential = $cred
    UseSsl = $true
}

# Send Email
Send-MailMessage @mailParam

Notes for Google Mail

  • This works with Gmail if the "less secure app" option is enabled but we should avoid enabling that.
  • Instead of "less secure app", enable 2-step authentication and use "Apps password"
  • Use port 465 if 587 does not work.

Solution 6 - Powershell

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.

Solution 7 - Powershell

#to send a .NET / C# powershell eMail use such a structure:

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", "[email protected]")
                                  .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 <[email protected]>",
                        "xxx <[email protected]>"
                        };

#body_msg this message can be overgiven as parameter to the method itself, HTML coding enabled!! #recipients never forget to use a string array in case of multiple recipients, otherwise only the last address in the string will be used!!!

#calling the function can look like this:

        mail reportMail = new mail(); //instantiate from class
        reportMail.sendEMailPowerShell(reportMessage, reportRecipient); //msg + email addresses

##ThumbUp

Solution 8 - Powershell

No need for all the complicated castings or splits into an array. I solved this simply by changing syntax from this:

$recipients = "[email protected], [email protected]"

to this:

$recipients = "[email protected]", "[email protected]"

Solution 9 - Powershell

My full solution to send mails to more recipients using Powershell and SendGrid on an Azure VM:


# Set your API Key here
$sendGridApiKey = '......your Sendgrid API key'
# (only API permission to send mail is sufficient and safe')

$SendGridEmail = @{

	# Use your verified sender address.
	From = '[email protected]'

	# Specify the email recipients in an array.
	To =  @('[email protected]','[email protected]')

	Subject = 'This is a test message via SendGrid'

	Body = 'This is a test message from Azure send by Powershell script on VM using SendGrid in Azure'
	
	# DO NO CHANGE ANYTHING BELOW THIS LINE
	SmtpServer = 'smtp.sendgrid.net'
	Port = 587
	UseSSL = $true
	Credential = New-Object PSCredential 'apikey', (ConvertTo-SecureString $sendGridApiKey -AsPlainText -Force)	
}

# Send the email
Send-MailMessage @SendGridEmail

Tested with Powershell 5.1 on one of my VMs in Azure.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionculterView Question on Stackoverflow
Solution 1 - PowershellCB.View Answer on Stackoverflow
Solution 2 - PowershellRubanovView Answer on Stackoverflow
Solution 3 - PowershellJohanView Answer on Stackoverflow
Solution 4 - PowershellAlexander ShapkinView Answer on Stackoverflow
Solution 5 - PowershellZunairView Answer on Stackoverflow
Solution 6 - PowershellmarkrView Answer on Stackoverflow
Solution 7 - PowershellRicardo FercherView Answer on Stackoverflow
Solution 8 - PowershellSpacefuzzView Answer on Stackoverflow
Solution 9 - PowershellAl-Noor LadhaniView Answer on Stackoverflow