74

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 <marcel@turie.eu>, Marcelt <marcel@nbs.sk>"

Get-ChildItem "C:\Decrypted\" | Where {-NOT $_.PSIsContainer} | foreach {$_.fullname} |
send-mailmessage -from "primasfrb@nbs.sk" `
            -to "$recipients" `
            -subject "New files" `
            -body "$teloadmin" `
            -BodyAsHtml `
            -priority  High `
            -dno onSuccess, onFailure `
            -smtpServer  192.168.170.61
culter
  • 5,487
  • 15
  • 54
  • 66

9 Answers9

101
$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.

CB.
  • 58,865
  • 9
  • 159
  • 159
  • 10
    Actually you don't need the 'human friendly' name. Make sure to unquote `$recipients` when you call it. So don't use `"$recipients"`but rather `$recipients`, and use the following format to fill it: `$recipients = "", ""` – DarkLite1 Jul 11 '14 at 17:52
  • 8
    Got it: `Send-MailMessage -To @('email@gmail.com','email2@gmail.com')` – Kellen Stuart Nov 14 '17 at 22:30
47

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")
MonkeyDreamzzz
  • 3,978
  • 1
  • 39
  • 36
13

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
Underverse
  • 1,271
  • 21
  • 32
Johan
  • 151
  • 1
  • 2
  • 3
    How about starting with a string array, like this `$recipients = @("Marcel ", "Marcelt ")` – user66001 Apr 06 '16 at 18:53
  • This approach is useful if the input is straight text. The split could be done on the same line: `$recipients = "Marcel ,Marcelt ".Split(',')` – Underverse Sep 06 '17 at 07:36
9

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

$to = "user1@domain.org;user2@domain.org"
$user = "italerts@domain.org"    
$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 <italerts@domain.org>"
    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.
Zunair
  • 1,085
  • 1
  • 13
  • 21
7

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
Alexander Shapkin
  • 1,126
  • 1
  • 13
  • 11
3

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

$recipients = "user1@foo.com, user2@foo.com"

to this:

$recipients = "user1@foo.com", "user2@foo.com"
Spacefuzz
  • 31
  • 1
2

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.

jonsca
  • 10,218
  • 26
  • 54
  • 62
markr
  • 21
  • 1
0

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", "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>"
                        };

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

Ricardo Fercher
  • 917
  • 6
  • 10
0

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 = 'my@email.com'

    # Specify the email recipients in an array.
    To =  @('person01@domainA.com','person02@domainB.com')

    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.

Al-Noor Ladhani
  • 2,413
  • 1
  • 22
  • 14