Powershell command to send email with the Column, Row and Data retrieved from the CSV file. If no data on CSV file, it will still send email but will be blank on the email body.

shaider007 101 Reputation points
2023-06-04T12:29:36.7966667+00:00

Hi,

I have below Powershell script that sends an email with an Excel CSV file attached.

I would like to know what do I need to change/add on below script so that it will just scan the contents of the CSV file and throw its content to the Outlook email body, so Column, Rows and data will be on the Outlook Body instead so no need for the CSV file to be attached on the email.

And if the Excel CSV file has nothing on it, Outlook will still send email but no column, rows and data in the body (Just like a blank email body).

So it will be easier for the recipient to look on the data instead of clicking the email then clicking the CSV file attached.

Thank you

Powershell command:

Get-ChildItem "C:\PowerShell\Result.csv" | Send-MailMessage -Credential $cred -to "xxxxxx@gmail.com" -from "xxxxxxx@gmail.com" -Subject "Testing" -body "This is a Test" -SmtpServer "mailhost.xxx.xxx.com" -Priority High

PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,320 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,831 Reputation points
    2023-06-04T15:15:11.5933333+00:00

    See if this works for you:

    $htmlfragment = Import-CSV C:\PowerShell\Result.csv | ConvertTo-Html -Fragment
    $x = @"
    <p>This is just a test</p>
    $htmlfragment
    "@
    
    Send-MailMessage -To you@dom.com -From me@dom.com -Subject "Just a test" -Body $x -BodyAsHtml -SmtpServer email@dom.com
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful