I have created this script that allows me to select a certain food item and the serving size and then it calculates nutritional value, adds it to a database, sums it all at the end of the day and sends me an email with an overview. It almost all works, I am just having trouble passing some variables from my script into the HTML formatted email.
In the portion of the code below, totals
is the data values from a spreadsheet range. I expect the retrieved values of calories
, caloriesFromFat
, and polyFat
to replace the matching text in the email's htmlBody
.
var calories = totals[0][25];
var caloriesFromFat = totals[0][26];
var polyFat = totals[0][27];
}
//Sends email with summary
MailApp.sendEmail({
to: "user@example.com",
subject: "Daily Intake Log",
htmlBody: <table style="width:100%">
<tr>
<td>Calories</td>
<td>calories</td>
</tr>
<tr>
<td>Calories From Fat</td>
<td>caloriesFromFat</td>
</tr>
<tr>
<td>PolyUnsaturated</td>
<td>polyFat</td>
</tr>
</table>
});
When I output the contents of the variables calories
, caloriesFromFat
, and polyFat
to the log they all contain the numbers they should. But when I get the email it doesn't insert the variables' contents, just leaves the name of the variables, e.g. calories
.
How do I get the computed values into my email?
The HTML must be a string (text), and you need to build the HTML with a text formula. Text strings in JavaScript are put together, (concatenated) with a plus sign:
var tableHTML = '<table style="width:100%">' + //Note single quotes on ends
"<tr><td>Calories</td><td>" +
calories +
"</td></tr>" +
"<tr><td>Calories From Fat</td><td>" +
caloriesFromFat +
"</td></tr>" +
"<tr><td>PolyUnsaturated</td><td>" +
polyFat +
"</td></tr>" +
"</table>";
If double quotes are used in the HTML attribute, then use single quotes on the ends of the string. Then just use the variable name for the email HTML:
htmlBody: tableHTML