Send-MailMessage每10分钟返回4.4.1连接超时

时间:2017-01-20 17:42:25

标签: powershell smtp

我有一个PowerShell脚本,可以从CSV文件导入的联系人列表中生成电子邮件:

# Get Credential
$Credential = & "C:\Powershell Scripts\Windows\Get-CredentialFromWindowsCredentialManager.ps1" ms.outlook.15:my.email@domain.com

# Get Contacts
$contacts = Import-Csv -Path "C:\Powershell Scripts\Email\Contacts.csv"

# Compose Email for each contact
foreach( $contact in $contacts )
{
    Write-Output "Creating email for: $($contact.FirstName) $($contact.LastName)"
    $To = "$($contact.FirstName) $($contact.LastName) <$($contact.Email)>"
    $From = "My Email <my.email@domain.com>"
    $Subject = "$($contact.FirstName), I have a suggestion for you!"
    $Body = "<html></html>"
    $SMTPServer = "smtp.office365.com"
    $Port = 587
    Send-MailMessage -To $To -From $From -Subject $Subject -SmtpServer $SMTPServer -Credential $Credential -UseSsl -Body $Body -BodyAsHtml -Port $Port

    # Due to the Message Send rate limit (30 per minute) I added this to slow the rate down
    Start-Sleep -Seconds 10
}

每隔10分钟我就会收到以下SMTP异常:

Send-MailMessage : Service not available, closing transmission channel. The
server response was: 4.4.1 Connection timed out. Total session duration:
00:10:08.3716645
At C:\Powershell Scripts\Email\SendEmail.ps1:17 char:2
+     Send-MailMessage -To $To -From $From -Subject $Subject -SmtpServer $SMTPServer  ...
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException
    + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage

我是否可以修改或更改代码中的任何设置以阻止此操作?

1 个答案:

答案 0 :(得分:2)

不要亲自接受这个,这只是一个普遍的咆哮,但是你有一个脚本可以对一个不受你控制的资源执行操作。因此,您不能期望SMTP连接成功,并想知道应该采取哪些措施来防止它失败。深呼吸。答案是考虑边缘情况并在代码中实际满足它们。当然,你已经在那里睡觉了尝试不会违反速率限制,但这不是一个强有力的解决方案。在这个例子中,围绕 Send-MailMessage 调用的简单异常处理程序就足够了。您可以包括一些重试和小睡眠延迟。

A&#34;可接受的最大故障数量&#34;阈值可用于打破重试循环并引起某种向内警报,等等。

长话短说,不要只是闭着眼睛把意大利面扔在墙上。

&LT; /咆哮&GT;

一个例子,但不一定是最整洁的解决方案:

df %>% 
  distinct %>%
  group_by(category) %>%
  summarise(uniques = sum(
    strings[group == 'A'] %!in% strings[group == 'B']))