我使用 Send-MailMessage 发送 HTML 电子邮件没有问题,但是有什么方法可以插入变量的值吗?
CSV:
email,samaccountname,newSAM,
jdoe@amce.com,john.doe,jdoe,
命令:
$html = (Get-Content .\email.html)
Import-Csv .\my-file.csv |
ForEach-Object {
Send-MailMessage -SmtpServer 10.0.0.1 -Subject "Subject Here" -From admin@acme.com -To $_.email -Priority: High -BodyAsHtml "$html"
}
HTML正文:
<html>
<head>
<title>HTML Generator Sample Page</title>
</head>
<body>
<p>
<span style="font-family:times new roman,times,serif;"><span style="font-size: 12px;"><strong>Old username: $_.samaccountname </strong></span></span></p>
<p>
<span style="font-family:times new roman,times,serif;"><span style="font-size: 12px;"><strong>New username: $_.newSAM </strong></span></span></p>
</body>
</html>
电子邮件正文显示 $_.newSAM 而不是从 .CSV 文件导入的值。
提前感谢您的任何帮助!
最佳答案
您必须自己替换占位符。
将您的 HTML 正文更改为此(注意 .NET 字符串格式占位符):
<html>
<head>
<title>HTML Generator Sample Page</title>
</head>
<body>
<p>
<span style="font-family:times new roman,times,serif;"><span style="font-size: 12px;"><strong>Old username: {0} </strong></span></span></p>
<p>
<span style="font-family:times new roman,times,serif;"><span style="font-size: 12px;"><strong>New username: {1} </strong></span></span></p>
</body>
</html>
然后,将您的代码更改为:
$html = Get-Content -Path $PSScriptRoot\email.html -Raw; # Get HTML text as one line
Import-Csv -Path $PSScriptRoot\my-file.csv |
ForEach-Object {
Send-MailMessage -SmtpServer 10.0.0.1 -Subject "Subject Here" -From admin@acme.com -To $_.email -Priority: High -BodyAsHtml ($html -f $_.samaccountname, $_.newSAM);
}
注意 : 在 PowerShell v3.0 及更高版本中,
$_
和 $PSItem
可以互换使用。
关于powershell - 使用 Send-MailMessage 将变量插入 html 正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22925614/