Casousadc
Casousadc

Reputation: 147

Sending E-mail to Multiple Recipients with Authentication

I am trying to send an e-mail through Powershell. I can send e-mails to one recipient without a problem using the code below. However, when I add a second recipient to the $EmailTo variable, I do not get the e-mail. I do not get any errors either. I did some research and it appears that the SMTP Client way of sending e-mails does not take multiple recipients.

$EmailFrom = "[email protected]" 
$EmailTo = "[email protected]"
$EmailBody = "Test Body" 
$EmailSubject = "Test Subject"
$Username = "[email protected]"
$Password = "12345"

$Message = New-Object Net.Mail.MailMessage($EmailFrom, $EmailTo, $EmailSubject, $EmailBody)
$SMTPClient = New-Object Net.Mail.SmtpClient("smtp.com", 123) #Port can be changed 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$SMTPClient.Send($Message)

I tried with the Send-MailMessage command but it is giving me issues.

Send-MailMessage -from $EmailFrom -to $EmailTo -Subject $EmailSubject `
  -smtpserver smtp.com -usessl `
  -credential (new-object System.NetworkCredential("$Username","$Password"))

The error I get with this is

Cannot find type [System.NetworkCredential]...

Any ideas on what the best way to send emails to multiple recipients with authentication would be?

Upvotes: 2

Views: 1493

Answers (2)

Kev
Kev

Reputation: 119806

Make sure you separate your $EmailTo address list with commas and don't pass as an array. i.e:

Do this:

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

Don't do this:

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

or this:

$EmailTo = "[email protected];[email protected]"

That last one would throw the following exception which you'd easily notice:

New-Object : Exception calling ".ctor" with "4" argument(s): "The specified string is not in the form required for an e-mail address."

Upvotes: 5

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200193

The class name is System.Net.NetworkCredential, not System.NetworkCredential.

Change this:

Send-MailMessage -from $EmailFrom -to $EmailTo -Subject $EmailSubject `
  -smtpserver smtp.com -usessl `
  -credential (new-object System.NetworkCredential("$Username","$Password"))

into this:

Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $EmailSubject `
  -SmtpServer smtp.com -UseSsl `
  -Credential (New-Object Net.NetworkCredential($Username, $Password))

and the problem should disappear.

Upvotes: 0

Related Questions