Question

I have no issues sending an HTML email using Send-MailMessage, but is there any way that I can insert the value of a variable?

CSV:

email,samaccountname,newSAM,
jdoe@amce.com,john.doe,jdoe,

Command:

$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 Body:

<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>

The email body shows $_.newSAM instead of the value imported from the .CSV file. Thanks in advance for any assistance!

Était-ce utile?

La solution

You have to substitute the placeholders yourself.

Change your HTML body to this (note the .NET string formatting placeholders):

<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>

Then, change your code to this:

$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);
}

NOTE: In PowerShell v3.0 and later, $_ and $PSItem can be used interchangeably.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top