Cannont read property 'namedValues' in Form Email Script - email

I have been trying to create an app script that will send a formatted email summary of each response to someone. I keep getting an error message returned for function onFormSubmit(e) { var responses = e.namedValues; The script is connected to the spreadsheet and not the form. I tried making the spreadsheet and then creating the form from the spreadsheet. I have deleted and reinstalled the triggers. From the other questions, I have been looking at if the e.namedValues is not working its because the script is connected to the form and not the sheet. I know that is not my problem here. This code was adapted from a project I used in the past that did work. So I am not sure what else to try. Any ideas or suggestions would be greatly appreciated.
var EMAIL_TEMPLATE_DOC_URL = 'google doc url';
var EMAIL_SUBJECT = 'Report Completed';
/**
* Installs a trigger on the Spreadsheet for when a Form response is submitted.
*/
function installTrigger() {
ScriptApp.newTrigger('onFormSubmit')
.forSpreadsheet(SpreadsheetApp.getActive())
.onFormSubmit()
.create();
}
/**
* Sends a customized email for every response on a form.
*
* #param {Object} event - Form submit event
*/
function onFormSubmit(e) {
var responses = e.namedValues;
// If the question title is a label, it can be accessed as an object field.
// If it has spaces or other characters, it can be accessed as a dictionary.
var email = 'name#gmail.com'();
var timestamp = responses.Timestamp[0];
var name = responses['Name of Staff Person completing form'][0].trim();
var researcht = responses['How much time did you spend researching?'][0].trim();
var mt = responses['How much time did you spend in meetings or doing tasks related to meetings?'][0].trim();
var wt = responses['How long did you spend practicing workshops?'][0].trim();
var rtt = responses['How long did you spend preparing for your Real Talk?'][0].trim();
var wpt = responses['How much time did you spend presenting workshops?'][0].trim();
var rtpt = responses['How much time did you spend hosting Real Talks?'][0].trim();
var misct = responses['How much time did you spend on miscellanous tasks?'][0].trim();
var topic1 = responses['First Topic Researched'][0].trim();
var topic2 = responses['Second Topic Researched'][0].trim();
var topic3 = responses['Third Topic Researched'][0].trim();
var meet1 = responses['First Meeting and Tasks'][0].trim();
var meet2 = responses['Second Meeting and Tasks'][0].trim();
var meet3 = responses['Third Meeting and Tasks'][0].trim();
var practicedw = responses['What workshop(s) did you practice?'][0].trim();
var practicedrt = responses['What Real Talk did you prepare for?'][0].trim();
var workshopname = responses['Name of Workshop Presented'][0].trim();
var workshopatt = responses['How many people attended your workshop?'][0].trim();
var workshopimp = responses['How could you improve your workshop presentation?'][0].trim();
var weval = responses['Did you email your workshop evaluations?'][0].trim();
var rtname = responses['Name of Real Talk'][0].trim();
var rtatt = responses['How many people attended your Real Talk?'][0].trim();
var rtimp = responses['How could you improve your Real Talk facilitation?'][0].trim();
var rteval = responses['Did you email your Real Talk evaluations?'][0].trim();
var misc1 = responses['Task 1'][0].trim();
var misc2 = responses['Task 2'][0].trim();
var misc3 = responses['Task 3'][0].trim();
var misc4 = responses['Task 4'][0].trim();
var concerns = responses['Third Topic Researched'][0].trim();
//get info for email
Utilities.sleep(1000);
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var lr = rows.getLastRow();
var isCellBlank = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1").getRange(1,1).isBlank();
// If there is at least one topic selected, send an email to the recipient.
var status = '';
if (!isCellBlank) {
MailApp.sendEmail({
to: email,
subject: EMAIL_SUBJECT,
htmlBody: createEmailBody(timestamp, name, researcht, mt, wt, rtt, wpt, rtpt, misct, topic1, topic2, topic3, meet1, meet2, meet3, practicedw, practicedrt, workshopname, workshopatt, workshopim, weval, rtname, rtatt, rtimp, rteval, misc1, misc2, misc3, misc4, concerns) ,
});
status = 'Sent';
}
else {
status = 'Email Not Sent';
}
// Append the status on the spreadsheet to the responses' row.
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getActiveRange().getRow();
var column = e.values.length + 1;
sheet.getRange(row, column).setValue(status);
Logger.log("status=" + status + "; responses=" + JSON.stringify(responses));
}
/**
* Creates email body and includes the links based on topic.
*
* #param {string} recipient - The recipient's email address.
* #param {string[]} topics - List of topics to include in the email body.
* #return {string} - The email body as an HTML string.
*/
function createEmailBody(timestamp, name, researcht, mt, wt, rtt, wpt, rtpt, misct, topic1, topic2, topic3, meet1, meet2, meet3, practicedw, practicedrt, workshopname, workshopatt, workshopim, weval, rtname, rtatt, rtimp, rteval, misc1, misc2, misc3, misc4, concerns) {
// Make sure to update the emailTemplateDocId at the top.
var docId = DocumentApp.openByUrl(EMAIL_TEMPLATE_DOC_URL).getId();
var emailBody = docToHtml(docId);
emailBody = emailBody.replace(/{{NAME}}/g, name);
emailBody = emailBody.replace(/{{timestamp}}/g, timestamp);
emailBody = emailBody.replace(/{{researcht}}/g, researcht);
emailBody = emailBody.replace(/{{mt}}/g, mt);
emailBody = emailBody.replace(/{{wt}}/g, wt);
emailBody = emailBody.replace(/{{rtt}}/g, rtt);
emailBody = emailBody.replace(/{{wpt}}/g, wpt);
emailBody = emailBody.replace(/{{rtpt}}/g, rtpt);
emailBody = emailBody.replace(/{{misct}}/g, misct);
emailBody = emailBody.replace(/{{topic1}}/g, topic1);
emailBody = emailBody.replace(/{{topic2}}/g, topic2);
emailBody = emailBody.replace(/{{topic3}}/g, topic3);
emailBody = emailBody.replace(/{{meet1}}/g, meet1);
emailBody = emailBody.replace(/{{meet2}}/g, meet2);
emailBody = emailBody.replace(/{{meet3}}/g, meet3);
emailBody = emailBody.replace(/{{practicedw}}/g, practicedw);
emailBody = emailBody.replace(/{{practicedrt}}/g, practicedrt);
emailBody = emailBody.replace(/{{workshopname}}/g, workshopname);
emailBody = emailBody.replace(/{{workshopatt}}/g, workshopatt);
emailBody = emailBody.replace(/{{workshopim}}/g, workshopim);
emailBody = emailBody.replace(/{{weval}}/g, weval);
emailBody = emailBody.replace(/{{ rtname}}/g, rtname);
emailBody = emailBody.replace(/{{rtatt}}/g, rtatt);
emailBody = emailBody.replace(/{{rtimp}}/g, rtimp);
emailBody = emailBody.replace(/{{rteval}}/g, rteval);
emailBody = emailBody.replace(/{{misc1}}/g, misc1);
emailBody = emailBody.replace(/{{misc2}}/g, misc2);
emailBody = emailBody.replace(/{{misc3}}/g, misc3);
emailBody = emailBody.replace(/{{misc4}}/g, misc4);
emailBody = emailBody.replace(/{{concerns}}/g, concerns);
return emailBody;
}
/**
* Downloads a Google Doc as an HTML string.
*
* #param {string} docId - The ID of a Google Doc to fetch content from.
* #return {string} The Google Doc rendered as an HTML string.
*/
function docToHtml(docId) {
// Downloads a Google Doc as an HTML string.
var url = "https://docs.google.com/feeds/download/documents/export/Export?id=" +
docId + "&exportFormat=html";
var param = {
method: "get",
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true,
};
return UrlFetchApp.fetch(url, param).getContentText();
}

I believe you are using the trigger builder wrong.
You would need to change this:
function installTrigger() {
ScriptApp.newTrigger('onFormSubmit')
.forSpreadsheet(SpreadsheetApp.getActive())
.onFormSubmit()
.create();
}
To this:
function installTrigger() {
var form = FormApp.openById('<YOUR_FORM_ID>');
ScriptApp.newTrigger('onFormSubmit')
.forForm(form)
.onFormSubmit()
.create();
}
You need to "link" the trigger to the form, not the spreadsheet.
Reference
onFormSubmit

Following Cooper's suggestion, I deleted the install trigger function. There were a few more problems with the script after that, so I made some edits. I will post the completed code, in case anyone is experiencing a similar problem.
var EMAIL_TEMPLATE_DOC_URL = 'document URL';
var EMAIL_SUBJECT = ' daily report summary for ';
var EMAIL_1 = 'name#gmail.com';
var EMAIL_2 = name#gmail.com';
//variable IDs
var timestampId = 1;
var nameId = 2;
var researchtId = 4;
var mtId = 8;
var wtId = 12;
var rttId = 14;
var wptId = 16;
var rtptId = 22;
var misctId = 29;
var topic1Id = 5;
var topic2Id = 6;
var topic3Id = 7;
var meet1Id = 9;
var meet2Id = 10;
var meet3Id = 11;
var practicedwId = 13;
var practicedrtId = 15;
var workshopnameId = 17;
var workshopattId = 18;
var workshopimpId = 19;
var wevalId = 20;
var rtnameId = 23;
var rtattId = 24;
var rtimpId = 25;
var rtevalId = 26;
var misc1Id = 30;
var misc2Id = 31;
var misc3Id = 32;
var misc4Id = 33;
var concernsId = 34;
var workstsId = 35;
function PrepEmail(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var lr = rows.getLastRow();
var responses = e.namedValues;
// If the question title is a label, it can be accessed as an object field.
// If it has spaces or other characters, it can be accessed as a dictionary.
var timestamp = sheet.getRange(lr,timestampId,1,1).getValue();
var name = sheet.getRange(lr,nameId,1,1).getValue();
var today = Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy");
var researcht = sheet.getRange(lr,researchtId,1,1).getDisplayValue();
var mt = sheet.getRange(lr,mtId,1,1).getDisplayValue();
var wt = sheet.getRange(lr,wtId,1,1).getDisplayValue();
var rtt = sheet.getRange(lr,rttId,1,1).getDisplayValue();
var wpt = sheet.getRange(lr,wptId,1,1).getDisplayValue();
var rtpt = sheet.getRange(lr,rtptId,1,1).getDisplayValue();
var misct = sheet.getRange(lr,misctId,1,1).getDisplayValue();
var topic1 = sheet.getRange(lr,topic1Id,1,1).getValue();
var topic2 = sheet.getRange(lr,topic2Id,1,1).getValue();
var topic3 = sheet.getRange(lr,topic3Id,1,1).getValue();
var meet1 = sheet.getRange(lr,meet1Id,1,1).getValue();
var meet2 = sheet.getRange(lr,meet2Id,1,1).getValue();
var meet3 = sheet.getRange(lr,meet3Id,1,1).getValue();
var practicedw = sheet.getRange(lr,practicedwId,1,1).getValue();
var practicedrt = sheet.getRange(lr,practicedrtId,1,1).getValue();
var workshopname = sheet.getRange(lr,workshopnameId,1,1).getValue();
var workshopatt = sheet.getRange(lr,workshopattId,1,1).getValue();
var workshopimp = sheet.getRange(lr,workshopimpId,1,1).getValue();
var weval = sheet.getRange(lr,wevalId,1,1).getValue();
var rtname = sheet.getRange(lr,rtnameId,1,1).getValue();
var rtatt = sheet.getRange(lr,rtattId,1,1).getValue();
var rtimp = sheet.getRange(lr,rtimpId,1,1).getValue();;
var rteval = sheet.getRange(lr,rtevalId,1,1).getValue();
var misc1 = sheet.getRange(lr,misc1Id,1,1).getValue();
var misc2 = sheet.getRange(lr,misc2Id,1,1).getValue();
var misc3 = sheet.getRange(lr,misc3Id,1,1).getValue();
var misc4 = sheet.getRange(lr,misc4Id,1,1).getValue();
var concerns = sheet.getRange(lr,concernsId,1,1).getValue();
var pname = name + '\'s';
var worksts = sheet.getRange(lr,workstsId,1,1).getDisplayValue();
// If there is at least one topic selected, send an email to the recipient.
var isCellBlank = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1").getRange(1,1).isBlank();
var status = '';
if (!isCellBlank) {
MailApp.sendEmail({
to: EMAIL_2 +','+ EMAIL_1,
subject: pname + EMAIL_SUBJECT + today,
htmlBody: createEmailBody(timestamp, name, today, worksts, researcht, mt, wt, rtt, wpt, rtpt, misct, topic1, topic2, topic3, meet1, meet2, meet3, practicedw, practicedrt, workshopname, workshopatt, workshopimp, weval, rtname, rtatt, rtimp, rteval, misc1, misc2, misc3, misc4, concerns) ,
});
status = 'Sent';
}
else {
status = 'Email Not Sent';
}
// Append the status on the spreadsheet to the responses' row.
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getActiveRange().getRow();
var column = e.values.length + 1;
sheet.getRange(row, column).setValue(status);
Logger.log("status=" + status + "; responses=" + JSON.stringify(responses));
}
/**
* Creates email body and includes the links based on topic.
*
* #param {string} recipient - The recipient's email address.
* #param {string[]} topics - List of topics to include in the email body.
* #return {string} - The email body as an HTML string.
*/
function createEmailBody(timestamp, name, today, worksts, researcht, mt, wt, rtt, wpt, rtpt, misct, topic1, topic2, topic3, meet1, meet2, meet3, practicedw, practicedrt, workshopname, workshopatt, workshopimp, weval, rtname, rtatt, rtimp, rteval, misc1, misc2, misc3, misc4, concerns) {
// Make sure to update the emailTemplateDocId at the top.
var docId = DocumentApp.openByUrl(EMAIL_TEMPLATE_DOC_URL).getId();
var emailBody = docToHtml(docId);
emailBody = emailBody.replace(/{{name}}/g, name);
emailBody = emailBody.replace(/{{today}}/g, today);
emailBody = emailBody.replace(/{{worksts}}/g, worksts);
emailBody = emailBody.replace(/{{timestamp}}/g, timestamp);
emailBody = emailBody.replace(/{{researcht}}/g, researcht);
emailBody = emailBody.replace(/{{mt}}/g, mt);
emailBody = emailBody.replace(/{{wt}}/g, wt);
emailBody = emailBody.replace(/{{rtt}}/g, rtt);
emailBody = emailBody.replace(/{{wpt}}/g, wpt);
emailBody = emailBody.replace(/{{rtpt}}/g, rtpt);
emailBody = emailBody.replace(/{{misct}}/g, misct);
emailBody = emailBody.replace(/{{topic1}}/g, topic1);
emailBody = emailBody.replace(/{{topic2}}/g, topic2);
emailBody = emailBody.replace(/{{topic3}}/g, topic3);
emailBody = emailBody.replace(/{{meet1}}/g, meet1);
emailBody = emailBody.replace(/{{meet2}}/g, meet2);
emailBody = emailBody.replace(/{{meet3}}/g, meet3);
emailBody = emailBody.replace(/{{practicedw}}/g, practicedw);
emailBody = emailBody.replace(/{{practicedrt}}/g, practicedrt);
emailBody = emailBody.replace(/{{workshopname}}/g, workshopname);
emailBody = emailBody.replace(/{{workshopatt}}/g, workshopatt);
emailBody = emailBody.replace(/{{workshopimp}}/g, workshopimp);
emailBody = emailBody.replace(/{{weval}}/g, weval);
emailBody = emailBody.replace(/{{rtname}}/g, rtname);
emailBody = emailBody.replace(/{{rtatt}}/g, rtatt);
emailBody = emailBody.replace(/{{rtimp}}/g, rtimp);
emailBody = emailBody.replace(/{{rteval}}/g, rteval);
emailBody = emailBody.replace(/{{misc1}}/g, misc1);
emailBody = emailBody.replace(/{{misc2}}/g, misc2);
emailBody = emailBody.replace(/{{misc3}}/g, misc3);
emailBody = emailBody.replace(/{{misc4}}/g, misc4);
emailBody = emailBody.replace(/{{concerns}}/g, concerns);
return emailBody;
}
/**
* Downloads a Google Doc as an HTML string.
*
* #param {string} docId - The ID of a Google Doc to fetch content from.
* #return {string} The Google Doc rendered as an HTML string.
*/
function docToHtml(docId) {
// Downloads a Google Doc as an HTML string.
var url = "https://docs.google.com/feeds/download/documents/export/Export?id=" +
docId + "&exportFormat=html";
var param = {
method: "get",
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true,
};
return UrlFetchApp.fetch(url, param).getContentText();
}

Related

BCC doesn't seem to function as an option of sendEmail - name and replyTo work though

function myFunction() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Welcome");
var targetSheet = ss.getSheetByName("Done");
var startRow = 2;
var lr = sheet.getLastRow();
var dataRange = sheet.getRange(startRow, 1, lr-1, 6);
var data = dataRange.getValues();
var colNumber = sheet.getLastColumn()-1;
var delRows = [];
for (var i = 0; i < data.length; i++) {
var row = data[i];
var id = row[0];
var emailAddress = row[1];
var date = row[2];
var city = row[3];
var bccmail = row[6];
var Sender = 'XXXXXX';
var reply = 'xxxxxx#xxxxxxx.com';
if (emailAddress.match('#') === null){
continue;
};
var subject = row[4];
var message = "Hey " + id + ", welcome in the team " + row[5];
MailApp.sendEmail(emailAddress, subject, message, {bcc: bccmail,name: Sender,replyTo: reply});
var targetRange = targetSheet.getRange(targetSheet.getLastRow()+1, 1, 1, colNumber);
var sourceRange = sheet.getRange(i+startRow, 1, 1, colNumber);
sourceRange.copyTo(targetRange);
delRows.push(i+startRow);
}
delRows.reverse().forEach(ri=>{sheet.deleteRow(ri)});
Almost all the script works fine. When it comes to sendEmail, I have tried to follow these guidelines and use sendEmail(recipient, subject, body, options). 2 out of 3 options work fine but BCC doesn't work at the moment. Do you know what I am doing wrong? Can BCC be a variable?
The problem is in this line:
var bccmail = row[6];
dataRange is defined as a range with only 6 columns. data is a 2D array with the values of dataRange. row is a 1D array with a single row of data. JavaScript array indexes only start at 0, so the values are in row[0] to row[5].
Please check your sheet in which column does the bcc string is defined and count the index from 0.
Reference:
Arrays in JavaScript

I'm trying to send an automated anniversary list. my code returns no errors but is sending no emails

function sendAnniversaryCampaing(){
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1FkKtSpvwecDEc6of2Nh37ud3qGgcNaK253S7jd7KqB0/edit#gid=0");// Sheet Url
var sheet = ss.getSheetByName("Sheet1");// Make Sure Sheet name matches at the bottom
var templateId = '157YoH_ngoESR-pwNUXfFj0dUwDYXBqOd6RCgB_cJVsQ';// the template doc with placeholders
var cDate = new Date(); //Present Day,
for(var i =2 ;i<=sheet.getLastRow(); i++){
var anDate = sheet.getRange(i,4).getValue(); // Date from SpreadSheet
if(cDate.getDate()==anDate.getDate()){
if(cDate.getMonth()==anDate.getMonth()){
var name = sheet.getRange(i,2).getValue();
var toMail= sheet.getRange(i,3).getValue();
sendMail(sheet,templateId,name,toMail);//sheet doesn't appear to be used in sendMail() Edited by Cooper.
sheet.getRange(i,5).setValue("Anniversary email sent");
}
}
}
}
function sendMail(sheet,templateId,name,toMail){
var docId = DriveApp.getFileById(templateId).makeCopy('temp').getId();
var doc = DocumentApp.openById(docId);// the temp copy
var body = doc.getBody();
body.replaceText('#name#',name);// update the temp doc
doc.saveAndClose();// save changes before conversion
var url = "https://docs.google.com/feeds/download/documents/export/Export?id="+docId+"&exportFormat=html";
var param = {
method : "get",
headers : {"Authorization": "Bearer" + ScriptApp.getOAuthToken()}
};
var htmlBody = UrlFetchApp.fetch(url,param).getContentText();
var trashed = DriveApp.getFileById(docId).setTrashed(true);// delete temp copy
MailApp.sendEmail(toMail,'Anniversary Campaing'+name,' ' ,{htmlBody : htmlBody});// send to myself to test
}
Try this:
function sendAnniversaryCampaing(){
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1FkKtSpvwecDEc6of2Nh37ud3qGgcNaK253S7jd7KqB0/edit#gid=0");// Sheet Url
var sheet = ss.getSheetByName("Sheet1");// Make Sure Sheet name matches at the bottom
var templateId = '157YoH_ngoESR-pwNUXfFj0dUwDYXBqOd6RCgB_cJVsQ';// the template doc with placeholders
var cDate = new Date().valueOf(); //Present Day,
for(var i=2;i<=sheet.getLastRow(); i++){
var anDate=new Date(sheet.getRange(i,4).getValue()).valueOf(); // Date from SpreadSheet
if(cDate==anDate){
var name=sheet.getRange(i,2).getValue();
var toMail= sheet.getRange(i,3).getValue();
sendMail(sheet,templateId,name,toMail);
sheet.getRange(i,5).setValue("Anniversary email sent");
}
}
}

Sending multiple attachments using Google Spreadsheet and Google Script

Im trying to send multiple attachments using Google Spreadsheet but I get the following error "Cannot retrieve the next object: iterator has reached the end."
It does work, because it sends the e-mail to the first email-address in the list, but it fails for the second one.
I have seen similar questions here about it, but no solutions resolve my issue.
Here is the script:
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 1;
var numRows = 2;
var dataRange = sheet.getRange(startRow, 1, numRows, 2);
var file1 = DriveApp.getFilesByName('Maandbrief December.pdf');
var file2 = DriveApp.getFilesByName('Weekendbrief 7-9 december.pdf');
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[0];
var message = row[1];
var subject = "Maandbrief December en weekendbrief 7-9 december";
MailApp.sendEmail({to:emailAddress, subject:subject, body:message, attachments: [file1.next(), file2.next()]})
}}
Thank you for your help.
Try this:
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 1;
var numRows = 2;
var dataRange = sheet.getRange(startRow, 1, numRows, 2);
var files1 = DriveApp.getFilesByName('Maandbrief December.pdf');
while(files1.hasNext()){var file1=files1.next();}
var files2 = DriveApp.getFilesByName('Weekendbrief 7-9 december.pdf');
while(files2.hasNext()){var file2=files2.next();}
var data = dataRange.getValues();
for (var i=0;i<data.length;i++) {
var row = data[i];
var emailAddress = row[0];
var message = row[1];
var subject = "Maandbrief December en weekendbrief 7-9 december";
MailApp.sendEmail({to:emailAddress, subject:subject, body:message, attachments: [file1, file2]})
}
}
or this:
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 1;
var numRows = 2;
var dataRange = sheet.getRange(startRow, 1, numRows, 2);
var n1=0;
var n2=0;
var files1 = DriveApp.getFilesByName('Maandbrief December.pdf');
while(files1.hasNext()){var file1=files1.next();n1++;}
var files2 = DriveApp.getFilesByName('Weekendbrief 7-9 december.pdf');
while(files2.hasNext()){var file2=files2.next();n2++}
var data = dataRange.getValues();
if(n1==1 && n2==1){
for (var i=0;i<data.length;i++) {
var row = data[i];
var emailAddress = row[0];
var message = row[1];
var subject = "Maandbrief December en weekendbrief 7-9 december";
MailApp.sendEmail({to:emailAddress, subject:subject, body:message, attachments: [file1, file2]});
}
}else{
throw('More than one file with given name.');
}
}

Reference Cell for Email Address

First code is what I am currently using, I am trying to get my email address to reference in a cell. I've found another script that does this but when I try to combine them, it doesn't work.
function getGoogleSpreadsheetAsExcel(){
try {
var ss = SpreadsheetApp.getActive();
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key="
+ ss.getId() + "&exportFormat=xlsx";
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
blob.setName(ss.getName() + ".xlsx");
MailApp.sendEmail("Email Address Here", "Subject Here", "Body of Email
Here", {attachments: [blob]});
} catch (f) {
Logger.log(f.toString());
}
}
And trying to combine this to it to reference cells for me instead of edited the script.
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(sheet.getSheetByName('Email Test'))
var startRow = 2; // First row of data to process
var numRows = 2; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 2)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var subject = "Sending emails from a Spreadsheet";
MailApp.sendEmail(emailAddress, subject, message);
}
}
Again both work on there own, but wont work when combined.
This is what I have compiled and it does send the email and attachement, but just to myself, no other recipients. Needing at least it to go to 6 other people at once.
function getGoogleSpreadsheetAsExcel(){
try {
var ss = SpreadsheetApp.getActive();
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key="
+ ss.getId() + "&exportFormat=xlsx";
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
blob.setName(ss.getName() + ".xlsx");
var sheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(sheet.getSheetByName('Email Test'))
var startRow = 2; // First row of data to process
var numRows = 2; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 2)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var subject = "Sending emails from a Spreadsheet";
MailApp.sendEmail(emailAddress, subject, message, {attachments: [blob]});
}
}
catch (f) {
Logger.log(f.toString());
}
}

Google Sheet sends email from list when cell condition met

I'm still very new to scripting and can't work out why the below script doesn't work
function sendReturnEmail(event) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var row = sheet.getActiveRange().getRow();
var cellvalue = ss.getActiveCell().getValue().toString();
if(event.range.getA1Notation().indexOf("K") && sheet.getRange("K" + row).getDisplayValue() == "Approved")
{
var rowVals = getActiveRowValues(sheet);
var aliases = GmailApp.getAliases();
var to = rowVals.user;
var subject = "Allocation request approved";
var body = "Your allocation request of " +rowVals.quantity + " cases on " + rowVals.date + " from " + rowVals.depot + " has been approved. <br \> <br \>"
+ "Regards, <br \> <br \>" +rowVals.analyst + "<br \> CPF Team";
Logger.log(aliases);
GmailApp.sendEmail(to,subject,body,
{from: aliases[0]})
;
}}
function getActiveRowValues(sheet){
var cellRow = sheet.getActiveRange().getRow();
// get depot value
var depotCell = sheet.getRange("E" + cellRow);
var depot = depotCell.getDisplayValue();
// get date value
var dateCell = sheet.getRange("F" + cellRow);
var date = dateCell.getDisplayValue();
// get quantity value
var quantCell = sheet.getRange("G" + cellRow);
var quant = quantCell.getDisplayValue();
// return an object with your values
var analystCell = sheet.getRange("J" + cellRow);
var analyst = analystCell.getDisplayValue();
var userCell = sheet.getRange("O" + cellRow);
var user = userCell.getDisplayValue();
return {
depot: depot,
date: date,
quantity: quant,
analyst: analyst,
user: user
} }
}
The sheet is question has several scripts running in it, one of them being this:
function onEdit() {
var s = SpreadsheetApp.getActiveSheet();
if( s.getName() == "Allocation Requests" ) { //checks that we're on the correct sheet
var r = s.getActiveCell();
if( r.getColumn() == 2) { //checks the column
var nextCell = r.offset(0, 13);
nextCell.setValue(Session.getEffectiveUser());
}
}
I now want the sheet to send an email to the email address captured using the above script (which works fine) when the corresponding cell in column K is manually changed to "Approved."
Can anyone see what I'm doing wrong. I get no errors when it runs, but I'm not getting an email. I've searched other questions but none have helped. Many thanks in advance.