2

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,
[email protected],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 [email protected] -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!

1 Answer 1

1

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 [email protected] -To $_.email -Priority: High -BodyAsHtml ($html -f $_.samaccountname, $_.newSAM);
}

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

Sign up to request clarification or add additional context in comments.

1 Comment

The semi-colon is a line terminator, and distinguishes lines of code more explicitly. It can help with debugging. The -f is the .NET string formatting operator. For more info, see about_Operators.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.