culter
culter

Reputation: 5697

Powershell send-mailmessage - email to multiple recipients

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

Upvotes: 76

Views: 366982

Answers (11)

Justin
Justin

Reputation: 985

try this:

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

aws ses send-email --to ($recipients -Split(",")) --from [email protected]

Upvotes: 0

Alec
Alec

Reputation: 1

I had this issue as well. Tried all the above solutions and was still having issues.

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

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

Creating an Array

$emailTo = $("[email protected]", "[email protected]", "[email protected]")

Implementing all of these resulted in only the last recipient in the array receiving the email.

My issue was in my

Send-MailMessage -From "$emailFrom" -To "$emailTo"

I had my $emailTo in double quotes "$emailTo"

When the quotes were removed from the Send-MailMessage, all three recipients got the email.

Upvotes: 0

Al-Noor Ladhani
Al-Noor Ladhani

Reputation: 2433

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.

Upvotes: 0

Spacefuzz
Spacefuzz

Reputation: 31

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]"

Upvotes: 3

Zunair
Zunair

Reputation: 1195

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.

Upvotes: 11

Johan
Johan

Reputation: 151

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

Upvotes: 13

Ricardo Fercher
Ricardo Fercher

Reputation: 977

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

Upvotes: 0

Alexander Shapkin
Alexander Shapkin

Reputation: 1262

To define an array of strings it is more comfortable to use $var = @('User1 ', 'User2 ').

$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

Upvotes: 7

MonkeyDreamzzz
MonkeyDreamzzz

Reputation: 4368

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")

Upvotes: 48

markr
markr

Reputation: 21

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.

Upvotes: 2

CB.
CB.

Reputation: 60956

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

Upvotes: 104

Related Questions