使用身份验证向多个收件人发送电子邮件

时间:2015-05-29 12:11:22

标签: email powershell

我正在尝试通过Powershell发送电子邮件。我可以使用下面的代码向一个收件人发送电子邮件而不会出现问题。但是,当我向$EmailTo变量添加第二个收件人时,我没有收到电子邮件。我也没有任何错误。我做了一些研究,看起来SMTP客户端发送电子邮件的方式不需要多个收件人。

$EmailFrom = "sender@email.com" 
$EmailTo = "recipient1@email.com"
$EmailBody = "Test Body" 
$EmailSubject = "Test Subject"
$Username = "carlos@email.com"
$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)

我尝试使用Send-MailMessage命令,但它给了我一些问题。

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

我得到的错误是

  

找不到类型[System.NetworkCredential] ...

有关通过身份验证向多个收件人发送电子邮件的最佳方式的任何想法都是?

2 个答案:

答案 0 :(得分:3)

请务必将您的$EmailTo地址列表与逗号分开,并且不要作为数组传递。即:

执行此操作:

$EmailTo = "recipient1@email.com,recipient2@email.com"

不要这样做:

$EmailTo = "recipient1@email.com","recipient2@email.com"

或者这个:

$EmailTo = "recipient1@email.com;recipient2@email.com"

最后一个会引发以下异常,您很容易注意到:

  

New-Object:异常调用" .ctor"用" 4"参数:"指定的字符串不是电子邮件地址所需的格式。"

答案 1 :(得分:0)

班级名称为System.Net.NetworkCredential,而不是System.NetworkCredential

改变这个:

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

进入这个:

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

问题应该消失。