google-apps-scriptnewsletter

Google App Script - Email body Returning [object Object]


Thanks for opening my thread! I'm running into a problem that i've been trying to solved all day and I just cant get my way around it.

Context: I've created and HTML newsletter design that I need to send to multiple people, that information will be on an excel.

I've successfully managed to create the loop and send the test emails. But the body of the email is simple [object Object]. I've placed some logger in the code to check that the template is linked properly and it is.

Any ideas what could be the problem I'm facing? Thanks!

PD. I'm very new to coding.

function sendEmails(){
const ss= SpreadsheetApp.getActiveSpreadsheet();
const sheet= ss.getActiveSheet();
const sheetValues = sheet.getDataRange().getValues();

const html= HtmlService.createTemplateFromFile('template');
const output = html.evaluate().getContent();
Logger.log(output);

for(let i = 1; i< sheetValues.length; i++){
  const row= sheetValues[i];
  const senderName = 'TEST EMAIL';
  const replyto = 'matias.saldana92@gmail.com';
  const cc ='';
  const subject = "April's Newsletter";
  const firstName=row[1];
  const lastName=row[2];
  const recipientEmail=row[3];
  const emailbody = {htmlBody:output};
  Logger.log(emailbody);

  const sendEmailtoCostumer=sendEmail(senderName,cc,subject,replyto,recipientEmail,emailbody)

  sheet.getRange(i + 1,6,1,1).setValue(sendEmailtoCostumer);
}
}
function sendEmail(senderName,cc,subject,replyto,recipientEmail,emailbody){
  
  try{
      MailApp.sendEmail(recipientEmail,subject,emailbody)
    const date = Utilities.formatDate(new Date(),'GMT-04:00','MM/dd/yyyy h:mm a');
    return 'Newsletter Sent on' + date;
    }
    catch(error){
      return error.message;
      }
}

Would love some help to understand what i'm doing wrong.


Solution

  • When you want to use {htmlBody:output} to MailApp.sendEmail, this is required to put to the 4th argument like sendEmail(recipient, subject, body, options). I thought that this might be the reason for your current issue. So, in your script, how about the following modification?

    From:

    MailApp.sendEmail(recipientEmail,subject,emailbody)
    

    To:

    MailApp.sendEmail(recipientEmail, subject, "", emailbody);
    

    References: