首页 > 解决方案 > File not attaching to email in powershell script

问题描述

I am creating a CSV file and trying to attach it to an email. Also doing this in the cloud so I want to bypass local drives...just create the file and attach it. But I'm getting this error...

You cannot call a method on a null-valued expression. At line:67 char:1 $smtp.Attachments.Add($att.Name)

Am I not attaching it the right way? The email is sending but with no attachment. I know it's being created because when I put it in an Azure container I can see it. But I want to do this without storing it first. This seems right. Thank you!

$SqlAdapter.Fill($DataSet)
$att = New-Item filename.csv -ItemType file
$DataSet.Tables[0] | Export-CSV -NoTypeInformation $att
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort)
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)  
$smtp.Attachments.Add($att)
$smtp.Send($From, $To, $subject, $body)

标签: powershellazure-powershell

解决方案


SmtpClient 类将需要一个Net.Mail.Attachment对象:

$att = New-Object Net.Mail.Attachment($file)

您构建对象而不是使用Send-MailMessagecmdlet 的任何原因?

Send-MailMessage -To $To -From $From -Subject $Subject -Body $Body -SmtpServer $SmtpServer -Attachments $PathToAttachment

推荐阅读