我正在使用以下Powershell脚本发送邮件
$smtpServer ="111.11.1.1.11"
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$msg=new-object Net.Mail.MailMessage
$msg.From="noreply@x.com"
$msg.To.Add("x@x.com")
$Success = $passed/$total*100;
$Failed = $Total- $Passed;
$msg.Subject = "BVT On Build"+$Buildno+",Total :"+ $Total+" Passed :"+
$Passed+" Failed :"+$Failed+"" #$subject
$msg.Body = "This is an autogenerated mail from VM - Total Tests Run
:"+$Total+" `n`n Total Tests Passed :"+ $Passed+" `n`n Pass Percentage
:"+$Success+" `n`n Failed test cases 'n'n"+$Failed+""
$smtp.Send($msg)
我在这里的要求是在电子邮件正文中为特定的变量值着色(例如:$ Failed in $ msg.Body)。我该如何实现呢?请您帮忙
我知道以下方法,但仅在写入主机中使用
Write-Host $myVariable -ForegroundColor 'Red'
我的输出应该是这样的 这是从VM自动生成的邮件-Total Tests Run 12 通过的总测试次数:6 及格率:50% 测试用例失败:6(红色)
答案 0 :(得分:1)
您将需要使用HTML
格式设置电子邮件正文中的颜色。
简单的IF/ELSE
条件表达式即可设置所需的颜色。另外,您必须将IsBodyHtml
属性设置为True
,以便邮件正文不会是纯文本。
$smtpServer ="111.11.1.1.11"
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$msg=new-object Net.Mail.MailMessage
$msg.From="noreply@x.com"
$msg.To.Add("x@x.com")
$Success = $passed/$total*100
$SuccessFormatted = if ($Success -ge 50){
'<font color="green">{0}</font>' -f $Success
}
else{
'<font color="red">{0}</font>' -f $Success
}
$Failed = $Total- $Passed;
$msg.Subject = "BVT On Build"+$Buildno+",Total :"+ $Total+" Passed :"+
$Passed+" Failed :"+$Failed+"" #$subject
$msg.Body = "This is an autogenerated mail from VM - Total Tests Run
:"+$Total+" `n`n Total Tests Passed :"+ $Passed+" `n`n Pass Percentage
:"+$SuccessFormatted+" `n`n Failed test cases 'n'n"+$Failed+""
$msg.IsBodyHtml = $true
$smtp.Send($msg)