htmlpowershellemailbatch-filecmd

Sending a multiple line body email from batch file using a PowerShell command


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="name1@company.com", "name2@company.com"
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

Solution

  • 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%"