power shell to read a txt file into msg body and send email

Hi ,
I need a power script to read a txt file and put the content of the txt file into message boy then email to me.

Please help!

Thanks
changjiaAsked:
Who is Participating?
 
evetsleepCommented:
param is used to provide a parameter for the script.

param([string]$file) allows for sendFile.ps1 -file  where -file is $file in param.  [string] basically tells PowerShell that the value entered after -file will be a string.  So if you were to do this:

.\sendfile.ps1 -file messageBody.txt

the string messgeBody.txt is stored in $file.  We then use Get-Content to .. well get the content of that file and store it in $fileData.

You 'could' hard code the file name if you wanted, and not use param, but I find it more useful to allow for parameters
0
 
evetsleepCommented:
Here is a basic way to do this.  Usage is .
\sendFile.ps1 -file test.txt.
param([string]$file)

[string]$fileData = Get-Content $file

if(!$fileData)
	{
	Write-Host "Nothing in File."
	break
	}

$msg = new-object system.net.mail.MailMessage
$SMTPClient = new-object system.net.mail.smtpClient
$SMTPServer = "smtpserver.domain.com"
$SMTPClient.host = $SMTPServer
$msg.From = "fromAddress@domain.com"
$msg.To.Add("toAddress@domain.com")
$msg.Subject = "Contents of $file"
$msg.Body = $fileData
$SMTPClient.Send($Msg)

Open in new window

0
 
changjiaAuthor Commented:
Hi evetsleep:

Thanks for the code. Could you explain to me what the param on line one does?
Also, what does [string]$ file do?

Thanks
0
 
changjiaAuthor Commented:
Got it. Thanks alot!
So, I see there is a 'if' statement to check if the file is empty, don't send.
My file has a header, so the first line always going to be in the file. How to check the file start from the second line?

Thanks
0
 
evetsleepCommented:
could you give an example of what the file would look like?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.