Reputation: 105
I am trying to write a batch file that will send an email using a PowerShell command. My only challenge is to add multiple lines to the email body.
I declare the message in a variable EmailBody and then I use it in PS command.
The problem is when I receive the email in Outlook 2016, ``r `n are just displayed as plain text.
I tried using HTML tags
but that fails because even tho I escape them with ^ in batch file, PowerShell sees ^ and does not like it.
@echo off
:: Log File Configuration
SET DateStamp=%date:~-4,4%%date:~-7,2%
SET LogFile=F:\WinSCP_%DateStamp%.log
:: Email Configuration
SET SMTPServer=server.com
SET EmailFrom=%computername%@company.com
SET EmailTo="[email protected]", "[email protected]"
SET EmailSubject=Subject
SET EmailAttachment=%LogFile%
SET EmailBody="Line1 Line2 Line3"
Some code
Powershell.exe -executionpolicy remotesigned -Command "& {Send-MailMessage -To '%EmailTo%' -From '%EmailFrom%' -Subject '%EmailSubject%' -SmtpServer '%SMTPServer%' -Body '%EmailBody%' -Attachments '%EmailAttachment%'}"
some code
Upvotes: 0
Views: 1658
Reputation: 11
This working for me.
Important for line break was -BodyAsHtml
and use <br>
set subject=Test BATCH with Log
set [email protected]
set EmailAttachment=%LogPath%%LogFile%
set "EmailBody=%row1%<br>%row2%"
powershell -ExecutionPolicy ByPass -Command "Send-MailMessage -SmtpServer 'smtp.ftn.local' -To '%email_to%' -From '[email protected]' -Subject '%subject%' -Body '%EmailBody%' -BodyAsHtml -Attachments %EmailAttachment% -Priority high"
Upvotes: 0
Reputation: 16236
Here is a revised version of the code from the question. Hopefully, this is also more readable than a one-liner. Writing it all in PowerShell would make it much more simple.
SET "EmailSubject=Subject"
SET "EmailBody=Line1 Line1`r`nLine2 Line2`r`nLine3 Line3"
SET "EmailAttachment=%USERPROFILE%\tp.txt"
powershell.exe -NoLogo -NoProfile -Command ^
"Send-MailMessage" ^
"-To %EmailTo%" ^
"-From '%EmailFrom%'" ^
"-Subject '%EmailSubject'" ^
"-SmtpServer '%SMTPServer%'" ^
"-Body '%EmailBody%'" ^
"-Attachments %EmailAttachment%"
Upvotes: 1
Reputation: 1
You should be able to enter `r`n wherever you want a line break, which PowerShell will evaluate to a carriage return and linefeed (i.e. a Windows style new line).
I would concur with the other replies that doing this in pure PowerShell is probably a better idea, however.
Upvotes: 0