【发布时间】:2019-09-28 13:35:27
【问题描述】:
我正在创建一个 PS 脚本来自动向 17k 用户发送电子邮件。我们的交易所安全基线设置为每分钟仅接受 60 个请求。因为我逐行(睡眠 1 秒)循环浏览电子邮件列表 (CSV),所以我的脚本需要几个小时才能完成。我现在想要实现的是将电子邮件发送给每个请求的 100 个用户。我正在研究如何将电子邮件存储在 100 个数组中并在发送下一个 100 个之前发送邮件。有什么建议吗?
$recipients = Get-Content "mailinglist.csv"
foreach($rcpt in $recipients)
{
Write-Host "Attempt sending email to $rcpt ..."
Send-MailMessage -ErrorAction SilentlyContinue -ErrorVariable SendError -From $From -to $rcpt -Subject $Subject -SmtpServer $SMTPServer -port $SMTPPort -UseSsl -Credential $Cred -BodyAsHtml ($Body -f $Subject, $Date, $Venue, $Description, $Image)
$ErrorMessage = $SendError.exception.message
If($ErrorMessage)
{
Write-Host "Failure - $ErrorMessage" -ForegroundColor Red
Start-Sleep -Seconds 60
Send-MailMessage -ErrorAction SilentlyContinue -ErrorVariable SendError -From $From -to $rcpt -Subject $Subject -SmtpServer $SMTPServer -port $SMTPPort -UseSsl -Credential $Cred -BodyAsHtml ($Body -f $Subject, $Date, $Venue, $Description, $Image)
}
ElseIf($SendError.exception.message -eq $null)
{
Write-Host "Email has been sent to $rcpt" -ForegroundColor Green
Start-Sleep -Seconds 1
$n++
}
}
Write-Host "Total sent = $n"
【问题讨论】:
-
您可能想添加一条说明,说明您为什么不使用为此类事情设计的服务之一。 [grin] ///// 这就是说,您可以通过按索引抓取它们来从数组中创建一批项目 - 有点像数组中的“切片”。
0..99,然后是100..199,等等…… -
您正在阅读 CSV 文件,就好像它只是单独一行的电子邮件地址列表一样。是这样的话,那很好,但如果它真的 IS 是 CSV,请显示前 3 或 4 行。正确的 CSV 具有标题并且可以包含多个字段。为此,请使用
Import-Csvcmdlet。这样,没有人知道你的$recipients数组中有什么。另外,我建议你使用 Splatting 来保持代码的可读性和可维护性。
标签: powershell