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

导入含邮箱地址的CSV遇问题,自动化邮件脚本报错

问题分析与解决步骤

核心错误原因

  • CSV里的邮箱地址末尾带多余分号;,不符合邮箱格式规范
  • 使用Import-Csv时错误加了-header参数,覆盖了CSV本身的表头,导致地址读取异常
  • 直接把对象数组$Addresses转成字符串传入BCC,系统无法识别为有效邮箱

修正步骤及脚本

  1. 先清理CSV文件:删掉两个邮箱地址末尾的分号,最终CSV内容如下:
EmailAddresses
First.Lastname@Domain.com
First.Lastname@Domain.com
  1. 修正后的PowerShell脚本:
$date = get-date -Format dd-MM-yyyy--hh-mm-SS
$Transcript = "$($PSScriptRoot)\Transcript\Transcript-$($date).txt"
Start-Transcript $Transcript

# 检查地址CSV文件路径
$checkCSVPath = Test-Path -Path "%FilePath%\Addresses.csv"
If(!($checkCSVPath)) {
    Write-Host -ForegroundColor red "Path failed"
    Exit
} else {
    Write-Host -ForegroundColor Green "Path found"
}

# 检查SMTP端口
$checkPort = test-netconnection '%SMTPAddress%' -port %%
If (!($checkPort) -or ($checkPort.TcpTestSucceeded -eq $false)) {
    Write-Host -foregroundcolor red "Port failed"
} Else {
    Write-Host -foregroundcolor Green "Port test complete"
}

# 检查邮件模板路径
$checkPath = Test-path -path "%FilePath%\Template\Email.htm"
if(!($checkPath)) {
    Write-Host -foregroundcolor red "Path failed"
    Exit
} else {
    Write-Host -ForegroundColor green "Path Found!"
}

# 读取CSV,已有表头无需指定-header
$Addresses = Import-Csv -path "%FilePath%\Addresses.csv"
$msg = new-object Net.Mail.MailMessage  
$smtp = new-object Net.Mail.SmtpClient "%SMTPAddress%"
$msg.From = "%FromAddress"
$msg.IsBodyHTML = $true

# 遍历每个地址添加到BCC,同时清理可能的空格
foreach ($addr in $Addresses) {
    $cleanedAddr = $addr.EmailAddresses.Trim()
    $msg.BCC.Add($cleanedAddr)
}

$msg.Subject = "%Subject%"
# 用-Raw参数确保HTML模板完整读取
$MailBody = Get-Content -path "%FilePath%\Template\Email.htm" -Raw
$msg.Body = $MailBody

# 发送邮件
$smtp.Send($msg)   
Write-Host -ForegroundColor green "Email Sent"       

Stop-Transcript

关键修正说明

  • 去掉Import-Csv的-header参数,让系统自动识别CSV自带的EmailAddresses表头
  • 遍历地址数组逐个添加到BCC,避免直接传入对象数组导致格式错误
  • 用Trim()处理地址可能存在的空格,提前手动清除CSV里的分号
  • 读取HTML模板时加-Raw参数,保证模板内容作为完整字符串传入,避免换行拆分问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 16:29:53