Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This is in JavaScript on Google Scripts. How do I get this to work? It says I ha

ID: 3858599 • Letter: T

Question

This is in JavaScript on Google Scripts.

How do I get this to work? It says I have an error when I am trying to replace; this is basically a simple mail merge program I wanted to try out.

function myFunction() {

var sheet = SpreadSheetApp.getActiveSheet(); //getting the active sheet that you are on

var data = sheet.getDataRange().getValues(); //getting the values for that sheet

var draft = MailApp.getDraftMessages()[1]; //make sure that it is the first draft in your drafts folder

var body = draft.getPlainBody(); //getting body of email - no HTML formatting

  

for (var i = 2; i < sheet.getMaxRows(); i++) {

var newDraft = draft; //copying everything into new draft

  

var name = data[i][0]; //name should be first column

var country = data[i][2]; //country should be third column

var university = data[i][3]; //university should be fourth column

  

var newDraft.replace("firstName", name); //replacing everything

var newDraft.replace("thisCountry", country);

var newDraft.replace("thisSchool", university);

  

MailApp.sendEmail(data[i][1], draft.getSubject(), draft); //sends email

delete newDraft;

}

}

Explanation / Answer

This is the working code now. There was just a silly mistake in it and that was first you have defined or we can say initialized the newDraft variable but you were defining it repeatedly which got the interpreter confused and that's why it was throwing error at each line. Hence, now it must work.

function myFunction() {
var sheet = SpreadSheetApp.getActiveSheet(); //getting the active sheet that you are on
var data = sheet.getDataRange().getValues(); //getting the values for that sheet

var draft = MailApp.getDraftMessages()[1]; //make sure that it is the first draft in your drafts folder
var body = draft.getPlainBody(); //getting body of email - no HTML formatting
  
for (var i = 2; i < sheet.getMaxRows(); i++) {
var newDraft = draft; //copying everything into new draft
  
var name = data[i][0]; //name should be first column
var country = data[i][2]; //country should be third column
var university = data[i][3]; //university should be fourth column
  
newDraft.replace("firstName", name); //replacing everything
newDraft.replace("thisCountry", country);
newDraft.replace("thisSchool", university);
  
MailApp.sendEmail(data[i][1], draft.getSubject(), draft); //sends email
delete newDraft;
}
}

Please rate the answer if it helped.......Thankyou

Hope it helps.....

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote