Use PS to email log file and include text in log in body of email

Hey Experts.  To make it even easier for our team, I want to include the contents of the log file in the body of the email.  The log file is currently sent as an attachment.  Thank you Experts.

$EmailFrom = "me.local"
$EmailTo = "us.local"
$EmailSubject = "Test"  
  
$SMTPServer = "smtp.srvr"
$emailattachment = $TodaysLog

$mailmessage = New-Object system.net.mail.mailmessage 
$mailmessage.from = ($emailfrom) 
$mailmessage.To.add($emailto)
$mailmessage.Subject = $emailsubject
$mailmessage.Body = $emailbody
$attachment = New-Object System.Net.Mail.Attachment($emailattachment, 'text/html')
  $mailmessage.Attachments.Add($attachment)


$mailmessage.IsBodyHTML = $true
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)  
#$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("$SMTPAuthUsername", "$SMTPAuthPassword") 
$SMTPClient.Send($mailmessage)

Open in new window

LVL 9
samiam41Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jose Gabriel Ortega CEE Solution Guide - CEO Faru Bonon ITCommented:
This question is similar to this one:
https://www.experts-exchange.com/questions/29073697/How-to-run-powershell-script-to-automate.html

Either way for the differences I've done the testing in my code and it's working:

#region EmailDetails
$From = "userFrom@domain.com"
$To = "destination@anydomain.com"
$Subject = "Test"  
$SMTPServer = "mail.j0rt3g4.com"
#$Attachment = "C:\Route\To\File\todayslog.log"
$Attachment = "D:\\lib\\Desktop\\20171215-Friday-ROME.html"
[string]$body = Get-Content $Attachment
$cred = New-Object pscredential -ArgumentList @($From, "PwdFromUserFrom" | ConvertTo-SecureString -AsPlainText -Force)
#endregion

Send-MailMessage -From $From -To $To -Subject $Subject -Attachments $Attachment  -SmtpServer $SMTPServer -Credential $cred -Body $body -BodyAsHtml

Open in new window


In the Send-Mailmessage Cmdlet I attached the parameter -BodyAsHtml, because my input file was an HTML so it can be formatted as required, you can remove this parameter without issues in case you're attaching any other type of input in your text file.

Note: You don't need to create a mail message object since PowerShell has a built-in cmdlet that sends emails and also manages authentication with the mail server.
1
samiam41Author Commented:
Thanks Jose.  I saw that script and was trying to make it work with my existing script but struggled with the hybrid.
0
Jose Gabriel Ortega CEE Solution Guide - CEO Faru Bonon ITCommented:
It's ok, give it a try and report any error I'm here :)
1
ON-DEMAND: 10 Easy Ways to Lose a Password

Learn about the methods that hackers use to lift real, working credentials from even the most security-savvy employees in this on-demand webinar. We cover the importance of multi-factor authentication and how these solutions can better protect your business!

oBdACommented:
Since you're sending this as html, some attention is required.
In the $EmailBody string variable you're currently using as body, insert {0} where you want the log text inserted, as in "<html>Whatever.<b />{0}</html>"
Then use this to send the email:
$EmailFrom = "me.local"
$EmailTo = "us.local"
$EmailSubject = "Test"  
$SMTPServer = "smtp.srvr"

$mailmessage = New-Object system.net.mail.mailmessage 
$mailmessage.from = ($emailfrom) 
$mailmessage.To.add($emailto)
$mailmessage.Subject = $emailsubject
$mailmessage.Body = $emailbody -f ("<br />$('='*72)<br />" + ((Get-Content -Path $TodaysLog) -join '<br />') + "<br />$('='*72)<br />")

$mailmessage.IsBodyHTML = $true
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)  
#$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("$SMTPAuthUsername", "$SMTPAuthPassword") 
$SMTPClient.Send($mailmessage)

Open in new window

1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
samiam41Author Commented:
Thanks oBdA for the script.  Could you help me understand where to put that code for the log text?  I'm trying to figure it out.  Also, I see you took a couple lines of code out from the original script I posted.  Do I need to leave them out?
0
oBdACommented:
I removed the lines referring to the now unused attachment.
What do you mean with "where to put that code for the log text"? You already seem to have an email body text in $EmailBody, however that's created - all you have to do is add {0} at whatever position inside the text you want the log content to appear. Line 10 will take care of the replacement.
1
samiam41Author Commented:
@Jose, there are four entries, is there a way to make each entry in the email body a separate line (this is how it looks in the log file)?

11:06 AM - No stale user accounts found.
11:06 AM - No accounts matched the criteria to be deleted.
11:06 AM - No stale user accounts found.
11:06 AM - No accounts matched the criteria to be deleted.

Right now, it does this:
4:03 PM - No stale user accounts found. 4:03 PM - No user accounts matched the criteria to be deleted. 4:03 PM - No stale computer accounts found. 4:03 PM - No PC accounts matched the criteria to be deleted.
0
Jose Gabriel Ortega CEE Solution Guide - CEO Faru Bonon ITCommented:
Sure:
#region EmailDetails
$From = "userFrom@domain.com"
$To = "destination@anydomain.com"
$Subject = "Test"  
$SMTPServer = "smtp.mailserver.com"
#$Attachment = "C:\Route\To\File\todayslog.log"
$Attachment = "D:\\lib\\Desktop\\ee\\Send Email a text file in body and as attachment\\log.log"
$body = (Get-Content $Attachment) -join "`n"
$cred = New-Object pscredential -ArgumentList @($From, "PwdFromUserFrom" | ConvertTo-SecureString -AsPlainText -Force)
#endregion

Send-MailMessage -From $From -To $To -Subject $Subject -Attachments $Attachment  -SmtpServer $SMTPServer -Credential $cred -Body $body -BodyAsHtml

Open in new window

0
samiam41Author Commented:
Good afternoon Jose.  I modified the script accordingly:
#region EmailDetails
$From = "me@local"
$To = "me@local"
$Subject = "Test"  
$SMTPServer = "smtp.local"
$Attachment = $TodaysLog
$body = (Get-Content $Attachment) -join "'n"
#endregion

Send-MailMessage -From $From -To $To -Subject $Subject -Attachments $Attachment  -SmtpServer $SMTPServer -Body $body -BodyAsHtml
}
}

Open in new window

Yields this:

2:47 PM - No stale user accounts found.'n2:47 PM - No user accounts matched the criteria to be deleted.'n2:47 PM - No stale computer accounts found.'n2:47 PM - No PC accounts matched the criteria to be deleted.

Please assist on making each entry a separate line.  Thank you sir!
0
samiam41Author Commented:
@ oBdA, not sure how else to ask this so maybe if I write it out, it will be easier to ask.  

$EmailFrom = "me.local"
$EmailTo = "us.local"
$EmailSubject = "Test"  
$SMTPServer = "smtp.srvr"

$mailmessage = New-Object system.net.mail.mailmessage 
$mailmessage.from = ($emailfrom) 
$mailmessage.To.add($emailto)
$mailmessage.Subject = $emailsubject
$mailmessage.Body = $emailbody -f ("<br />$('='*72)<br />" + ((Get-Content -Path $TodaysLog) -join '<br />') + "<br />$('='*72)<br />") <html>Whatever.<b />{0}</html>

$mailmessage.IsBodyHTML = $true
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)  
#$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("$SMTPAuthUsername", "$SMTPAuthPassword") 
$SMTPClient.Send($mailmessage)

Open in new window

Oddly enough, it caused this error:

At line:107 char:137
+ ... ='*72)<br />") <html>Whatever.<b />{0}</html>
+                    ~
The '<' operator is reserved for future use.
At line:107 char:155
+ ... ml>Whatever.<b />{0}</html>
+                    ~~
Unexpected token '/>' in expression or statement.
At line:107 char:160
+ ... atever.<b />{0}</html>
+                    ~
The '<' operator is reserved for future use.
At line:54 char:8
+ } Else {
+        ~
Missing closing '}' in statement block.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : RedirectionNotSupported

So, here's the question rephrased.  I'm guessing the html code has to be put in a certain place in the line.  Could you please provide that location or an example?
0
oBdACommented:
No, you don't have to change anything in that line.
I've mentioned this before: in your question in line 12, you already have
$mailmessage.Body = $emailbody
which obviously is the body of the email when the log was sent as attachment.
Where does $emailbody come from? How/when is it set, and to what?
0
samiam41Author Commented:
@Jose, I found the right coding
#region EmailDetails
$From = "me@local"
$To = "me@local"
$Subject = "Test"  
$SMTPServer = "smtp"
$Attachment = $TodaysLog
$body = (Get-Content $Attachment) + $line -join "<br>"
#endregion

Send-MailMessage -From $From -To $To -Subject $Subject -Attachments $Attachment  -SmtpServer $SMTPServer -Body $body -BodyAsHtml
}
}

Open in new window


Line #7- $body = (Get-Content $Attachment) + $line -join "<br>"
0
oBdACommented:
The minimum should be something like
$emailbody = "<html>Here's the log:<b />{0}</html>"
## ...

Open in new window

1
samiam41Author Commented:
oBdA, that was the explanation I was missing.  I removed that $emailbody and boom, it worked!  Great job, as always.  Your script is good to go.
0
samiam41Author Commented:
My apologies folks.  I could have sworn I closed this and awarded points.
0
samiam41Author Commented:
Thanks Experts!  Again, my apologies for not closing this out sooner.  Holidays made time a black-hole.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.

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.