I have been working with Google Apps Script lately and found a way to send HTML email containing a table in Google Sheets https://spreadsheet.dev/send-html-email-from-google-sheets#:~:text=Search%20for%20Content%2DType%3A%20text,the%20document%20except%20this%20HTML. But I am not able to configure how I should be doing this with multiple tables (4 in my case) in a single mail only?
function sendEmail() {
var stockData = getData();
var body = getEmailText(stockData);
MailApp.sendEmail({
to: "youremail@example.com",
subject: "Stock update",
body: body
});
}
function getEmailText(stockData) {
var text = "";
stockData.forEach(function(stock) {
text = text + stock.name + "\n" + stock.ticker + "\n" + stock.price + "\n-----------------------\n\n";
});
return text;
}
/**
* @OnlyCurrentDoc
*/
function getData() {
var values = SpreadsheetApp.getActive().getSheetByName("Data").getRange("Stocks").getValues();
values.shift(); //remove headers
var stocks = [];
values.forEach(function(value) {
var stock = {};
stock.name = value[0];
stock.ticker = value[1];
stock.price = value[2];
stocks.push(stock);
})
//Logger.log(JSON.stringify(stocks));
return stocks;
}
The above code works perfectly well for a single table. What modifications can I make to have multiple tables? Any help will be much appreciated.
I believe your goal is as follows.
#ffffff
. This is from your sample images. image1 , image2 .In your script, the values from the named range are not converted to the HTML. And, your script used one named range. I thought that this might be the reason for your issue.
In order to achieve your goal, how about the following flow?
When this flow is reflected in a sample script, it becomes as follows.
In this sample script, in order to covert from the richtext to HTML, " RichTextApp " of a Google Apps Script library is used. So before you use this script, please install the library .
function myFunction() {
const namedRanges = ["sampleNamedRange1", "sampleNamedRange2",,,]; // Please set your named ranges in this array.
const emailAddress = "youremail@example.com"; // Please set the email address.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const { htmls, backgounds } = namedRanges.reduce((o, r) => {
const range = ss.getRangeByName(r);
o.htmls.push(RichTextApp.RichTextToHTMLForSpreadsheet({ range }));
o.backgounds.push(range.getBackgrounds());
return o;
}, { htmls: [], backgounds: [] });
const tables = htmls.map((v, i) => `table ${i + 1}<br><table border="1" style="border-collapse: collapse"><tr style="background: ${backgounds[i][0][0]};">${v.map(r => "<td>" + r.join("</td><td>")).join("</tr><tr>")}</tr></table>`);
MailApp.sendEmail({ to: emailAddress, subject: "Stock update", htmlBody: tables.join("<br>") });
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.