Skipping blank emails in Google Apps Script Mail Merge

丶灬走出姿态 提交于 2019-12-13 07:25:23

问题


I'm using this Simple Mail Merge Tutorial to help me create a mail merge to send students and their parents a summary of their completed community service hours. Their email addresses are in a Google Sheets doc. The script works until it hits a blank cell. Then it gives me an error that says "Invalid email: undefined" with a reference to the line in the script with the send email command.

I've temporarily solved this within the spreadsheet itself by having it plug in a dummy email into any blank cell, but I'd like to just write it into the script to ignore blank cells.

The full code is at the link above. I've modified that code to draw from three columns of email addresses in the sheet instead of one. The critical bit is this:

function sendEmails() {


var ss = SpreadsheetApp.getActiveSpreadsheet();
  var dataSheet = ss.getSheets()[0];
  var dataRange = dataSheet.getRange(5, 1, dataSheet.getMaxRows() - 1, 7);

  var templateSheet = ss.getSheets()[1];
  var emailTemplate = templateSheet.getRange("B7").getValue();

  // Create one JavaScript object per row of data.
  objects = getRowsData(dataSheet, dataRange);

  // For every row object, create a personalized email from a template and send
  // it to the appropriate person.
  for (var i = 0; i < objects.length; ++i) {
    // Get a row object
    var rowData = objects[i];

// Generate a personalized email.
// Given a template string, replace markers (for instance ${"First Name"}) with
// the corresponding value in a row object (for instance rowData.firstName).
var emailText = fillInTemplateFromObject(emailTemplate, rowData);
var emailSubject = templateSheet.getRange("B6").getValue();

MailApp.sendEmail(rowData.studentEmail, emailSubject, emailText);
MailApp.sendEmail(rowData.parentaEmail, emailSubject, emailText);
MailApp.sendEmail(rowData.parentbEmail, emailSubject, emailText);
  } 

What do I need to add to skip blank cells in the parentaEmail and parentbEmail columns?


回答1:


There are a number of ways to solve your issue, but in general, you just need a conditional statement that says 'if the cell is not empty, execute the sendMail function.'

if (rowData.parentaEmail != '') {
  MailApp.sendEmail(rowData.parentaEmail, emailSubject, emailText);
}



回答2:


Ok, I've got it working now. Thanks rGil for setting me on the right path. Here's what ended up working:

   if (rowData.parentaEmail != null) {
      MailApp.sendEmail(rowData.parentaEmail, emailSubject, emailText);
   }

and then do the same thing again but for parentbEmail



来源:https://stackoverflow.com/questions/23855986/skipping-blank-emails-in-google-apps-script-mail-merge

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!