发送电子邮件问题

时间:2019-05-16 10:39:14

标签: powershell powershell-v2.0 powershell-v3.0

当尝试附加.CSV文件并运行代码时,我收到以下错误消息:“使用“ 1”自变量调用“发送”的异常:“无法发送给所有收件人。”

我尝试使用.txt文件($ attachment =“ \ path1 \ test.txt”),并且执行了相同的代码,没有任何错误(但是我没有收到任何邮件)

$date_value = Get-Date -format yyyy_MM_dd
$file_Name = 'test_'+ $date_value.ToString() + '.csv'
$attachment = "\\path1\test.CSV"
$smtpserver = "server.com" 
$size=((Get-item $attachment ).length) -as [Int]

$from = "mail.com" 
[string[]]$To= "xyz@xyz.com"
$CC="xyz@xyz.com"
$Subject = "Test"
$body=@"

Hi,
Test
Regards,
Team
"@ 

$message = new-object System.Net.Mail.MailMessage ( $From , $To )
$message.CC.Add($cc) 
$message.Subject = $Subject 
$attach = new-object Net.Mail.Attachment($attachment) 
$message.Attachments.Add($attach) 
$message.body = $body 
$smtp = new-object Net.Mail.SmtpClient($smtpserver) 
if ($size -gt 0){
$smtp.Send($message) 
}
$attach.Dispose()
$message.Dispose()
$smtp.Dispose()

期望:.CSV文件应附加并通过电子邮件发送

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用Send-MailMessage选项的-Attachment cmdlet?非常简单。

Send-MailMessage -To $To -From $from -Cc $CC -Subject $Subject -Attachments $attachment -Body $body -SmtpServer $smtpserver