Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell send-mailmessage - email to multiple recipients

Tags:

powershell

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 
like image 255
culter Avatar asked Apr 20 '12 07:04

culter


People also ask

Can I use PowerShell to send email?

The Send-MailMessage cmdlet sends an email message from within PowerShell. You must specify a Simple Mail Transfer Protocol (SMTP) server or the Send-MailMessage command fails. Use the SmtpServer parameter or set the $PSEmailServer variable to a valid SMTP server.

What can I use instead of MailMessage?

NET MailKit. The most generic method that would replace SmtpClient and Send-MailMessage would be the recommended replacement, which is MailKit. This is a third-party, open-source library but maintained by a Microsoft employee and officially recommended for use in the documentation.

How do I pass credentials in PowerShell MailMessage?

I was able to make it work with this command: PS > Send-MailMessage -smtpServer smtp.gmail.com -Credential $credential -Usessl true -from '[email protected]' -to '[email protected]' -subject 'Testing' -attachment C:\CDF. pdf .


2 Answers

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

like image 172
CB. Avatar answered Sep 18 '22 18:09

CB.


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") 
like image 43
Rubanov Avatar answered Sep 21 '22 18:09

Rubanov