Reputation: 451
I'm trying to attach CSV data to an email but "Send-MailMessage" does not accept it as an -attachment parameter. I want to avoid creating a file. Is there a way to send the content straight to the email as an attachment.
$attachment = $DataSet.Tables[0] | ConvertTo-Csv -NoTypeInformation
Send-MailMessage
-From $from
-To $to
-Subject $subject
-Body $emailbody
...
-Attachments $attachment
Upvotes: 0
Views: 566
Reputation: 174920
No, not using Send-MailMessage
anyways.
The -Attachments
parameter accepts paths to files, not arbitrary string data:
# create a temp file
$tmpFile = [System.IO.Path]::GetTempFileName()
# export data to file
$DataSet.Tables[0] | Export-Csv -NoTypeInformation -Path $tmpFile.FullName
# rename to something sensible
$tmpFile = (Rename-Item $tmpFile -NewName "report.csv" -PassThru).FullName
# send mail
Send-MailMessage ... -Attachments $tmpFile
# clean up
Remove-Item $tmpFile
If you don't mind re-implementing much of Send-MailMessage
by hand, you might be able to create the attachment from memory without writing it to disk:
$msg = [System.Net.Mail.MailMessage]::new()
# ...
$attachmentData = $DataSet.Tables[0] | ConvertTo-Csv -NoTypeInformation
$attachment = [System.Net.Mail.Attachment]::CreateAttachmentFromString(($attachmentData -join [environment]::NewLine), "report.csv")
$msg.Attachments.Add($attachment)
# ...
Upvotes: 2