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

使用Send-MailMessage cmdlet发送附件失败:邮件仅含主题与正文

解决Send-MailMessage附件无法发送的问题

嘿,我来帮你排查这个附件发不出去的问题!首先咱们先拆解一下你的命令,然后一步步找原因~

先说说命令里的小误区

你的命令里Export-Csv之后直接管道到Send-MailMessage其实是没用的——因为Export-Csv只负责把数据写入文件,不会输出任何对象到管道,所以后面的Send-MailMessage其实是独立运行的。不过这不是附件没发送的直接原因,但咱们先把这个逻辑理顺。

附件无法发送的核心原因及修复方案

1. 附件文件不存在或路径写错了

你指定的附件路径是"C:\Users\User1\File.txt",首先得确认这个文件真的在这个位置:

  • 手动打开C:\Users\User1文件夹看看有没有File.txt
  • 或者在PowerShell里跑这个命令验证:Test-Path "C:\Users\User1\File.txt",如果返回False,说明文件不存在,要么修正路径,要么确保文件已经创建好。

2. 没有读取附件文件的权限

如果文件确实存在,但你的PowerShell会话没权限读取它,Send-MailMessage会悄悄跳过这个附件(不会报错,这点特别坑)。可以试试:

  • 右键点击PowerShell,选择「以管理员身份运行」再执行命令
  • 或者右键File.txt→「属性」→「安全」,检查当前用户有没有读取权限

3. 优化命令结构(避免误解)

如果你的本意是把导出的wrongOU.csv也作为附件发送,那得调整命令顺序——先导出文件,再单独调用Send-MailMessage,这样逻辑更清晰,也不容易出问题:

# 先导出AD查询结果到CSV文件(加上-NoTypeInformation避免多余的类型行)
Get-ADComputer -Filter {operatingsystem -like '*server*'} | 
    Where-Object { 
        $_.distinguishedname -notlike '*production*' -and 
        $_.distinguishedname -notlike '*tbd*' -and 
        $_.distinguishedname -notlike '*disabled*' -and 
        $_.distinguishedname -notlike '*domain controll*' 
    } | 
    Select-Object Name, Distinguishedname | 
    Export-Csv -Path C:\Users\User1\wrongOU.csv -NoTypeInformation

# 再发送邮件,可同时添加多个附件
Send-MailMessage -From 'from.email@gmail.com' -To 'to.email@gmail.com' `
    -Subject 'This is a test email.' -SmtpServer smtp.test.com `
    -Attachments "C:\Users\User1\wrongOU.csv", "C:\Users\User1\File.txt" `
    -Body 'This is a test email.'

如果确实只需要发送File.txt,也建议分开执行命令,避免管道带来的混淆:

# 先执行AD查询导出(如果不需要这个文件可以跳过这步)
Get-ADComputer -Filter {operatingsystem -like '*server*'} | 
    Where-Object { 
        $_.distinguishedname -notlike '*production*' -and 
        $_.distinguishedname -notlike '*tbd*' -and 
        $_.distinguishedname -notlike '*disabled*' -and 
        $_.distinguishedname -notlike '*domain controll*' 
    } | 
    Select-Object Name, Distinguishedname | 
    Export-Csv -Path C:\Users\User1\wrongOU.csv -NoTypeInformation

# 单独发送邮件,确保附件路径正确
Send-MailMessage -From 'from.email@gmail.com' -To 'to.email@gmail.com' `
    -Subject 'This is a test email.' -SmtpServer smtp.test.com `
    -Attachments "C:\Users\User1\File.txt" `
    -Body 'This is a test email.'

4. 开启错误排查模式

如果还是不行,给Send-MailMessage加上-ErrorAction Stop参数,让它直接抛出错误信息,这样就能精准定位问题了:

Send-MailMessage -From 'from.email@gmail.com' -To 'to.email@gmail.com' `
    -Subject 'This is a test email.' -SmtpServer smtp.test.com `
    -Attachments "C:\Users\User1\File.txt" `
    -Body 'This is a test email.' -ErrorAction Stop

比如如果是文件找不到,这里会直接提示“无法找到路径中的一部分”,如果是权限问题,会提示“拒绝访问”,一目了然。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:26:26