简体   繁体   中英

PowerShell e-mail - sending .csv in body with HTML

I have a powershell script that runs a mysql query, and exports the output to a .csv file.

It then imports it, sends it to a $body variable and e-mails it.

Here is the code

### Script to write body of e-mail to $body variable ###

$body = @"
CHECK 4A - MONTH DATABASE REPORT

Row count should be between 3-4k, but less on a Monday.

"@  + (Import-CSV  C:\Users\*****\Documents\Reports\result4A.csv | Out-String)

I want to use a bit of HTML in the e-mail too, just to make it a bit easier to read, so I used the -BodyAsHtml parameter:

### Send e-mail ###

send-mailmessage -from " Daily Check <server@company.com>" -to "Admin <e-mail@company.com>" -BodyAsHtml -subject "Daily Server Checks Report" -body "$body" -priority High -dno onSuccess, onFailure -smtpServer **.*.*.**

The problem is that this means the .csv file isn't displayed correctly in the e-mail, as the e-mail body is changed to HTML. Is there any way around this? I would like to keep the export to .csv solution if possible.

$csvHTML = Import-Csv C:\Users\*****\Documents\Reports\result4A.csv  | ConvertTo-Html

$body = @"
    ....  
"@ + ($csvHTML[5..($csvHTML.length-2)] | Out-String)

This will convert the CSV file to HTML . Then you can simply select <table></table> tags that contain the CSV (skip first 5 and last 2 lines) and add it to the body of your email.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM