使用Send-MailMessage将变量插入到html正文中

时间:2014-04-08 00:41:56

标签: powershell powershell-v3.0

使用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文件导入的值。 提前感谢您的任何帮助!

1 个答案:

答案 0 :(得分:0)

您必须自己替换占位符。

将您的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可以互换使用。