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 "@gmail.com" -from "x@gmail.com" -Subject "Testing" -body "This is a Test" -SmtpServer "mailhost.xxx.xxx.com" -Priority High

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 47,901 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 ******@dom.com -From ******@dom.com -Subject "Just a test" -Body $x -BodyAsHtml -SmtpServer ******@dom.com
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.