Sending Email to Multiple Recipients

Share |

Join PowerShell.com!
Subscribe to Feed

PowerShell eBook
Sign up for
Your PowerTip of the Day:

Award-winning PowerShellPlus


Admin Guide to PowerShell Remoting


Mastering PowerShell eBook

Send-MailMessage can send emails to multiple recipients. You just need to make sure the list of recipients is provided as an array. When you call Send-MailMessage via command line, that's a no-brainer. Simply use a comma-separated list:

PS> Send-MailMessage -From someone@email.de -To someone@email.de, anotherone@scriptinternals.de -Subject Testmessage -Body 'A test message' -SmtpServer smtp.web.de -Credential (Get-Credential)

If you'd rather like to wrap Send-MailMessage in your own function to make usage easier and implement some basic error handling, then make sure you declare the -To parameter as string array and not as string.

Here is a function that can send mails to multiple recipients. Just fill in the placeholders with your SMTP server and credentials:

function Send-Mail {
    param(
     [Parameter(Mandatory=$true)]
     [String[]]
     $To,
        
     [Parameter(Mandatory=$true)]
     $Body,
     $Subject = 'Email from YOURNAME',
     $From = 'YOURNAME@company.com',
     $SmtpServer = 'YOURSMTPSERVER',
     $Credential = $(New-Object System.Management.Automation.PSCredential('YOURLOGONNAME', 'YOURLOGONPASSWORD' | ConvertTo-SecureString -AsPlainText -Force))
    )

    try {
      Send-MailMessage -To $To -Body $Body -Subject $Subject -From $From -SmtpServer $SMTPServer -Credential $Credential -ErrorAction Stop
      Write-Host 'Email successfully sent.' -ForegroundColor Green
    }
    catch {
        Write-Host "Email did not go through: $_" -ForegroundColor Red
    }
} 

Now, sending emails is as simple as this:

PS> Send-Mail someone@email.de, someoneelse@scriptinternals.de 'This is a mail message I wanted to fire off to all of you...'

Twitter This Tip! ReTweet this Tip!


Posted Apr 23 2012, 06:00 AM by ps1
Copyright 2012 PowerShell.com. All rights reserved.