Powershell EMail:如何在电子邮件正文中添加新行?

Powershell EMail: How to add new line in email Body?

Powershell 的新手。编写了运行良好的 powershell 脚本,但是当它发送邮件时,它不会在正文中显示换行符。以下是配置:

$EmailFrom = "monitoring@mydomainname.no"
$EmailTo = "fatherazrael@tcs.com"
$Subject = "Disk Space Low: $server"

$Body = "Server Name:  $server, <NEED NEW LINE> Drive: C,  <NEED NEW LINE>  Total Size: $sizeGB,  <NEED NEW LINE> Space Left: $freeSpaceGB"

$SMTPServer = "scan.opinergo.fn"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
#$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("<From mail ID>", "Password");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)   

在 Body 中,我使用以下代替 ;搜索范围:

1) %0d%0a - 用户检查邮件时不工作

2)\n - 当用户检查邮件时不工作

3)
- 用户检查邮件时不工作

任何人都可以建议我还可以使用什么来获取新行或脚本中需要的任何修改吗?

(来自我的评论)

PowerShell 换行符是 `n(反引号-n),所以:

$Body = "Server Name:  $server, <NEED NEW LINE> Drive: C

变成:

$Body = "Server Name:  $server, `n Drive: C

PowerShell 换行符是 n, and can only be used in double quotes. Single quotes will print the actual "n".

$Body = "Server Name:  $server, <NEED NEW LINE> Drive: C"

变为:

$Body = "Server Name:  $server,`nDrive: C"

我不确定这些其他用户是如何让 `n 创建一个新行的,但我永远无法让它工作...

相反,我最终做了以下事情...

  • 使用 -BodyAsHtml 开关
  • 使用 <br />(中断)html 标签

例如...

powershell -ExecutionPolicy ByPass -Command Send-MailMessage -BodyAsHtml -SmtpServer 'myemail.server.com' -To 'Mr To <to@server.com>' -From 'Mr From <from@server.com>' -Subject 'Reports From Daily SQL Backup Jobs' -Body 'There was an issue backing up the databases and sending them to the virtual drive.<br />Test Line 2.<br />Test Line 3.-more on line 3<br />Test Line 4.<br />EOF<br />'"

技术上需要

$body = "first line" + "`n" + "second line"

否则,第一行创建为尾部,第二行创建为前导 space。

尽管我的版本是 4.0.不确定您使用的是哪个版本,或者这是否有影响。

$Body = "Server Name:  $server
Drive: C
Total Size: $sizeGB
Space Left: $freeSpaceGB"