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

无法通过PowerShell脚本发送邮件,请求技术排查与解决

解决PowerShell通过Office365 SMTP发送邮件失败问题

脚本中的直接错误

  • 引号格式错误:$To = "abhishek.chawla@duckcreek.com”结尾的引号是中文全角格式,会触发语法错误,需改为英文半角引号。
  • 冗余的收件人处理:先给$To赋值,又通过$recipients重新拆分赋值,完全多余,直接定义数组格式收件人即可。
  • 端口类型错误:$SMTPPort被定义为字符串,Send-MailMessage的-Port参数要求整数类型,需修正。

Office365 SMTP核心配置要求

  • 必须启用TLS 1.2及以上版本:你的脚本已配置TLS1.2,这部分没问题,但要确保服务器系统支持该协议。
  • 账户SMTP权限:发送邮箱JIT.Batch@duckcreek.com需开启SMTP客户端访问权限,Exchange Online中可通过以下命令启用:
    Set-CASMailbox -Identity "JIT.Batch@duckcreek.com" -SmtpClientAuthenticationDisabled $false
    
  • 密码与验证方式:
    • 若账户启用MFA,普通密码无法用于SMTP验证,需使用应用密码替代。
    • 微软已逐步淘汰SMTP基本验证,长期方案建议改用Microsoft Graph API发送邮件。

修正后的脚本

# 启用TLS 1.2+协议
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 -bor [System.Net.SecurityProtocolType]::Tls13

# 邮件基础配置
$From = "JIT.Batch@duckcreek.com"
$To = @("abhishek.chawla@duckcreek.com")
$Cc = "abhishek.chawla@duckcreek.com"
$Subject = "JITAppointment batch Started on StateAuto Production"
$Body = "JITAppointment batch Started on SA Production for latest file"

# SMTP服务器配置
$SMTPServer = "smtp.office365.com"
$SMTPPort = 587

# 凭据设置(替换为实际密码或应用密码)
$secpasswd = ConvertTo-SecureString "你的实际密码" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential($From, $secpasswd)

# 发送邮件
Send-MailMessage -From $From -To $To -Cc $Cc -Subject $Subject -Body $Body -BodyAsHtml `
    -SmtpServer $SMTPServer -Port $SMTPPort -UseSsl -Credential $mycreds

额外排查步骤

  1. 测试网络连通性:在服务器执行Test-NetConnection smtp.office365.com -Port 587,确认能正常连接。
  2. 检查防火墙/代理:确保服务器防火墙、代理允许出站访问587端口。
  3. MFA账户替代方案(推荐):使用Microsoft Graph API发送邮件(需提前在Azure AD注册应用)
    # 先安装模块:Install-Module Microsoft.Graph.Mail
    Import-Module Microsoft.Graph.Mail
    
    # 连接Graph API(替换为你的应用信息)
    Connect-MgGraph -ClientId "你的应用ID" -TenantId "你的租户ID" -ClientSecret (ConvertTo-SecureString "你的应用密钥" -AsPlainText -Force)
    
    # 构建邮件对象
    $message = @{
        subject = $Subject
        body = @{
            contentType = "HTML"
            content = $Body
        }
        toRecipients = @(
            @{
                emailAddress = @{
                    address = $To[0]
                }
            }
        )
        ccRecipients = @(
            @{
                emailAddress = @{
                    address = $Cc
                }
            }
        )
    }
    
    # 发送邮件
    Send-MgUserMail -UserId $From -Message $message -SaveToSentItems:$true
    

内容的提问来源于stack exchange,提问作者Abhi Chawla

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 14:10:35