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

PowerShell使用Send-MailMessage发邮件报错修复与代码简化求助

PowerShell Send-MailMessage 发送Office365邮件修复方案

报错根因说明

  • 首次Credential转换报错:Send-MailMessage的-Credential参数仅接受PSCredential类型对象,原代码传入System.Net.NetworkCredential类型不匹配
  • 二次STARTTLS报错:Office365 SMTP 587端口强制要求TLS加密,原代码未添加-UseSsl参数开启加密
  • 其他语法问题:Attachments参数前缺少破折号、-Port参数值错误加引号、函数定义名与调用名不匹配、多余Workflow包装(普通函数即可满足需求)

优化后可运行代码

使用参数 splatting 写法更简洁易维护,完全对齐原有Net.Mail版本的功能:

function Send-Mail {
    "Sending Email"

    # 读取预生成的加密密码构建合法凭证
    $emailPassword = Get-Content "C:\scriptfolder\password.txt" | ConvertTo-SecureString
    $emailCredential = [System.Management.Automation.PSCredential]::new("sender@domain.com", $emailPassword)

    # 邮件参数配置
    $mailConfig = @{
        From = "sender@domain.com"
        To = "user1@domain.com"
        Cc = "user2@domain.com", "user3@domain.com"
        Subject = "***TEST***"
        Body = "***TEST****"
        Attachments = "替换为实际附件的绝对路径"
        DeliveryNotificationOption = "OnSuccess", "OnFailure"
        SmtpServer = "smtp.office365.com"
        Port = 587
        UseSsl = $true
        Credential = $emailCredential
    }

    Send-MailMessage @mailConfig
    "Email Sent"
}

# 调用发送函数
Send-Mail

注意事项

  • 附件路径建议写绝对路径,避免PowerShell工作目录变动导致找不到文件
  • 若不需要送达通知可删除DeliveryNotificationOption配置项

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 08:27:03