Home > Software design >  Using Powershell and HTMLBody.Replace how do I replace values inside an existing table?
Using Powershell and HTMLBody.Replace how do I replace values inside an existing table?

Time:01-24

I have an existing email template file for Outlook with To, CC, Subject and Body prefilled.

I can replace the values I need on the subject just fine, however, when it comes to the HTMLBody part, it only replaces values outside the table; I've tested this by putting all 15 placeholders outside the table.

In Powershell, I defined an array with the items that will be replaced and another that reads the values from a JSON file, then I loop through both in order to replace the values on the HTMLBody.

This is the code in question:

$emailToreplaceValues=@(
  "[DailyReportDate]",
  "[DailyReportSuccess]",
  "[DailyReportFailure]",
  "[DailyReportFailureRate]"
)

$newValues=@(
    $valuesJSON.DailyReport.Date,
    $valuesJSON.DailyReport.Success,
    $valuesJSON.DailyReport.Failure,
    $dailyReportFailureRate
  )

$reportEmail = $outlookObj.CreateItemFromTemplate("$emailTemplate")
  $reportEmail.Subject = $reportEmail.Subject.Replace("[date]", $date)

  for($i=0;$i -le $newValues.Count;$i  ) {
    $reportEmail.HTMLBody = $reportEmail.HTMLBody.Replace($emailToreplaceValues[$i], $newValues[$i])
  }

There's more values but for the sake of brevity, I only included a few of the values, from my understanding, the issue is that some of those values are inside a HTML table cell but I don't know if I can access the table or cells directly.

CodePudding user response:

Firstly, do not use MailItem.HTMLBody property as variable - it is expensive to set and read, and it might not be the same HTML you set as Outlook performs some massaging and validation. Introduce an explicit variable, set it to the value of HTMLBody, do all your string replacements in a loop using that variable, then set the MailItem.HTMLBody property once.

You can also try to output the value of that variable to make sure the old values to be replaced are really there and are not broken by HTML formatting or encoding.

CodePudding user response:

For the sake of future reference, the only way I was able to fix this, was by grabbing the html code off the email that I based my email template off.

I organized it so that any tags I want replaced are in their own line without anything else other than the spaces for indentation, then defined it as a variable that goes through the replace cycle and gets assigned to the MailItem.HTMLBody property after the replace cycle.

  • Related