Chris Bisset
Chris Bisset

Reputation: 13

Sending mail with HTML body using for in Google Apps Script

I'm making a very basic mail merge from Google Sheets using Google Apps Script. I have text that needs to be presented as html, but when it sends the message body has '[object Object]' rather than the HTML content.

function test(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var howmany = ss.getRangeByName("howmany").getValue();
var emails = ss.getRangeByName("email").getValues();
var subjects = ss.getRangeByName("subject").getValues();
var text = ss.getRangeByName("text").getValues();

for (var i = 0; i < howmany; i++) {
MailApp.sendEmail(emails[i],subjects[i],{htmlBody: text[i]});
}

Upvotes: 1

Views: 12691

Answers (3)

ScampMichael
ScampMichael

Reputation: 3728

get values is a two-dimensional array even if its only one column wide.

Try:

MailApp.sendEmail(emails[i][0],subjects[i][0],"",{htmlBody: text[i][0]});

Upvotes: 3

David
David

Reputation: 3184

text[i] is currently a javascript object, the function sendEmail expects a string representing the body of the email. This printing of [object Object] occurs when a javascript object is printed in Google App Script.

You need to specify the non-html body, and/or the html body as, see specification, a String.

sent to the function sendEmail(recipient, subject, body, options). Also within the options hash the value assigned to the htmlBody needs to be a String.

I recommend you use Logger.log(text[i]); to check that what is in text[i] is what you expect.

Upvotes: 0

Tmdean
Tmdean

Reputation: 9299

Checking the API docs, it looks like you need to use a different overload of sendEmail.

MailApp.sendEmail(emails[i], subjects[i], text[i], { htmlBody: text[i] });

The fourth argument is a JS object that sets advanced options. This is what the docs say about htmlBody:

if set, devices capable of rendering HTML will use it instead of the required body argument; you can add an optional inlineImages field in HTML body if you have inlined images for your email

So I would recommend you also provide a plain text version of the third argument, to support people who are using email that can't display HTML.

Upvotes: 1

Related Questions