You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell的Office 365邮件发送脚本中添加重试/最大尝试次数

为PowerShell Office 365邮件脚本添加重试功能

我们可以通过循环+错误捕获的方式实现重试逻辑,核心思路是:当Send-MailMessage执行失败时,捕获错误信息,等待指定时长后重新尝试,直到发送成功或达到设定的最大重试次数。

以下是修改后的完整脚本:

$UserName = "xxx@xxx.com"      # 账号
$Password = ConvertTo-SecureString "SFDSFWSDSFSFW" -AsPlainText –Force # 密码(建议改为从安全存储读取,比如本地凭据管理器或Azure密钥保管库)
$cred = New-Object System.Management.Automation.PSCredential($UserName,$Password)
$from = new-object System.Net.Mail.MailAddress("xxx@xxx.com", "SCM")
$TLS12Protocol = [System.Net.SecurityProtocolType] 'Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $TLS12Protocol

# 重试配置参数
$maxRetries = 3  # 最大重试次数
$retryDelaySeconds = 10  # 每次重试间隔的秒数

## 1 发送给V290
## 定义Send-MailMessage参数
$mailParams = @{
    SmtpServer                 = 'smtp.office365.com'
    Port                       = 587 # 587是标准TLS端口,不推荐使用25
    UseSSL                     = $true
    BodyasHtml                 = $true
    Credential                 = $cred
    From                       = $from
    To                         = 'AAA@outlook.com'
    Cc                         = 'BBB@outlook.com','CCC@outlook.com'
    Subject                    = "AR Report"
    Body                       = 'Dears,'
    Attachments                = 'C:\AutoJob\xxx\Output_Files\V290.xlsx'
    Encoding                   = [System.Text.Encoding]::UTF8 # 明确指定编码,避免默认编码导致的乱码问题
}

# 重试执行逻辑
$retryCount = 0
$sendSuccess = $false

while (-not $sendSuccess -and $retryCount -lt $maxRetries) {
    try {
        Write-Host "尝试发送邮件(第 $($retryCount + 1) 次)..."
        Send-MailMessage @mailParams -ErrorAction Stop
        $sendSuccess = $true
        Write-Host "邮件发送成功!"
    }
    catch {
        $retryCount++
        Write-Warning "邮件发送失败:$($_.Exception.Message)"
        if ($retryCount -lt $maxRetries) {
            Write-Host "将在 $retryDelaySeconds 秒后重试..."
            Start-Sleep -Seconds $retryDelaySeconds
        }
        else {
            Write-Error "已达到最大重试次数($maxRetries 次),邮件发送最终失败。"
        }
    }
}

关键说明:

  • 重试配置:$maxRetries和$retryDelaySeconds可根据实际网络状况调整,比如网络波动大时可增加重试次数或延长间隔。
  • 错误捕获:通过-ErrorAction Stop确保所有执行错误都会进入catch块,避免遗漏隐性错误。
  • 状态跟踪:用$sendSuccess标记发送状态,$retryCount控制循环终止条件,确保不会无限重试。
  • 安全提示:脚本中硬编码密码存在泄露风险,建议改用Get-Credential交互式输入,或从安全存储中读取凭据。

内容的提问来源于stack exchange,提问作者Hill James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 00:32:36