用于发送批量电子邮件的PowerShell脚本

时间:2018-01-19 05:40:25

标签: xml powershell email

我在下面编写了一个脚本,用于从XML文件中读取电子邮件ID。加载使用组ID过滤的电子邮件ID,然后将电子邮件发送到该ArrayList上的所有电子邮件ID。我不知道下面的问题是什么,我没有收到任何电子邮件。

function Test {
   function Send-Mail {
        Param($smtp, $from, $to, $subject, $body)
        $smtp = New-Object System.Net.Mail.SmtpClient($smtp)
        $mail = New-Object System.Net.Mail.MailMessage
        $mail.From = $from
        $mail.To.Add($to)
        $mail.Subject = "subject goes here"
        $mail.Body = "This is test"
        $smtp.Send($mail)
    }
    #Read the xml file and typecast it to System.Xml.XmlDocument
    [Xml]$XmlData = Get-Content Email.xml
    $ArrayEmail = New-Object System.Collections.ArrayList
    $subject = "Testing PowerShell email"
    $from = "a@134.com"
    $smtp = "test.test123.com"
    $body = "The body goes here"
    #get the email list from group id
    $ArrayEmail = $XmlData.emaillist.group |
                  Where-Object {$_.id -eq "IT"} |
                  Select-Object emailid
    $to = New-Object System.Collections.ArrayList
    #store the email ids in array
    for ($i = 0; $i -lt $ArrayEmail.emailid.Count; $i++) {
        $to.Add($ArrayEmail.emailid[$i])
    }
    Send-Mail -Smtp $smtp -From $from -To $to[$i] -Subject $subject -Body $body
 }

以下是我的示例XML文件:

<emaillist>
  <group id="IT">
    <emailid>a@123.com</emailid>
    <emailid>b@345.com</emailid>
  </group>
  <group id="Admin">
    <emailid>admin@admin.com</emailid>
  </group>
</emaillist>

不确定我做错了什么或错过任何事情,因为一切似乎都没问题。但我仍然没有收到任何电子邮件。我的smtp一切都很好,发件人和收件人的电子邮件都很好。

1 个答案:

答案 0 :(得分:3)

你所拥有的是off-by-one error。在for循环完成后,循环变量$i的值是$to 的最高索引加一个。因此,$to[$i]评估为$null,因为您在 ArrayList中的最后一个元素(不存在)之后尝试访问元素,并且PowerShell返回$null之类的东西,而不是抛出错误。

替换它:

$ArrayEmail = $XmlData.emaillist.group |
              Where-Object {$_.id -eq "IT"} |
              Select-Object emailid
$to = New-Object System.Collections.ArrayList
#store the email ids in array
for ($i = 0; $i -lt $ArrayEmail.emailid.Count; $i++) {
    $to.Add($ArrayEmail.emailid[$i])
}
Send-Mail -Smtp $smtp -From $from -To $to[$i] -Subject $subject -Body $body

用这个:

$to = $XmlData.emaillist.group |
      Where-Object {$_.id -eq "IT"} |
      Select-Object -Expand emailid
Send-Mail -Smtp $smtp -From $from -To $to -Subject $subject -Body $body

问题就会消失。

要将邮件发送给所有收件人,您需要逐个添加邮件:

function Send-Mail {
    Param($smtp, $from, $to, $subject, $body)
    $smtp = New-Object System.Net.Mail.SmtpClient($smtp)
    $mail = New-Object System.Net.Mail.MailMessage
    $mail.From = $from
    $to | ForEach-Object { $mail.To.Add($_) }
    $mail.Subject = "subject goes here"
    $mail.Body = "This is test"
    $smtp.Send($mail)
}

但是,您应该使用Send-MailMessage cmdlet,而不是重新发明轮子,而其他人已经建议:

Send-MailMessage -SmtpServer $smtp -From $from -To $to -Subject $subject -Body $body