I know this is a very old post but I thought I would give my input after being in a similar position.
The below is a basic function that I have written to create a CSV attachment from an object etc.
One of the main issues with getting this to work was firstly convertto-csv
outputs everything in quotes (I know this has been fixed PS6 +, but not useful when using PS5. Secondly when casting the CSV data to a string and converting it to a memory stream it was escaping Carriage Return / Line Feed, to get around this I appended [System.Environment]::NewLine
to every row in the CSV.
Function ConvertTo-CSVEmailAttachment {
Param(
[Parameter(Mandatory=$true)]
[String]$FileName,
[Parameter(Mandatory=$true)]
[Object]$PSObject,
$Delimiter
)
If ($Delimiter -eq $null){$Delimiter = ","}
$MS = [System.IO.MemoryStream]::new()
$SW = [System.IO.StreamWriter]::new($MS)
$SW.Write([String]($PSObject | convertto-csv -NoTypeInformation -Delimiter $Delimiter | % {($_).replace('"','') + [System.Environment]::NewLine}))
$SW.Flush()
$MS.Seek(0,"Begin") | Out-Null
$CT = [System.Net.Mime.ContentType]::new()
$CT.MediaType = "text/csv"
Return [System.Net.Mail.Attachment]::new($MS,$FileName,$CT)
}
To use this you would require to have your object ready as their is no pipeline functionality taken into consideration (As I said basic function).
Example:
$ADList = get-aduser -filter * -properties Telephonenumber | where Telephonenumber -ne $Null | select givenname, surname, telephonenumber |sort surname
$EmailAttachment = ConvertTo-CSVEmailAttachment -FileName "ADList.CSV" -PSObject $ADList
One of the answers is correct in the sense that Send-MailMessage
requires a string to a file path to function.
However you can use the .net library [Net.Mail.MailMessage]
to create the email instead of using Send-MailMessage
:
$SMTPserver = "This.Will.Be.Your.Email.Server.Endpoint"
$from = "SomeEmailAddress@yourdomain.com"
$to = "Recipient@domain.com"
$subject = "This is the subject Line"
$emailbody = "This is the body of the email"
$mailer = new-object Net.Mail.SMTPclient($SMTPserver)
$msg = new-object Net.Mail.MailMessage($from, $to, $subject, $emailbody)
$msg.Attachments.Add($EmailAttachment) #### This uses the attachment made using the function above.
$msg.IsBodyHTML = $false
$mailer.send($msg)
Anyway I hope this helps someone that is in a similar situation in the future.