I am not sure how can I add a line for cc. Below is the script i have. Grateful if anyone can help. Thanks!
Meanwhile, I know there is a trigger called onFormSubmit trigger. May I know how can I send an email according to the specific answer coming in from a form?
For instance, in the Google form. I have question like Which colour do you like? Red or Yellow. If someone picked yellow, an email would be sent. However, I am not sure how to do that.
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Send Email",
functionName : "sendEmails"
}
];
sheet.addMenu("Let's do it", entries);
};
function hindex(header_row, value){
for (var j = 0; j < header_row.length; j++) {
if(value == header_row[j]) return j;
}
return 0;
}
function sendEmails() {
var htmlcode = String(SpreadsheetApp.getActiveSpreadsheet().getSheetByName("HTML").getRange(1, 1).getValue());
var replyTo = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sender").getRange(2, 2).getValue();
var name_shown = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sender").getRange(1, 2).getValue();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Receiver List");
var htmlsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Testhtml");
var startRow = 2; // First row of data to process
var LastRow = sheet.getLastRow(); // Number of rows to process
var dataRange = sheet.getRange(startRow, 1, LastRow-1, 50);
var data = dataRange.getValues();
for (var i = 1; i < data.length; i++) {
var row = data[i];
var name = row[0];
var emailAddress = row[1];
var subject = row[2];
var confirm = row[3];
var EmailSent = row[4];
var strings = data[0];
var obj = {};
var message = htmlcode;
for (var k = 0; k < strings.length; k++){
if(strings[k].length == 0)continue;
obj[strings[k]] = row[hindex(data[0],strings[k])];
var reg = new RegExp("\{\{"+strings[k]+"\}\}", "g");
//htmlsheet.getRange(k+1, 3).setValue(reg);
message = message.replace(reg,obj[strings[k]])
}
/*
var r1 = row[hindex(data[0],"r1")];
var r2 = row[hindex(data[0],"r2")];
var r3 = row[hindex(data[0],"r3")];
var r4 = row[hindex(data[0],"r4")];
var r5 = row[hindex(data[0],"r5")];
var r6 = row[hindex(data[0],"r6")];
var r7 = row[hindex(data[0],"r7")];
var r8 = row[hindex(data[0],"r8")];
var r9 = row[hindex(data[0],"r9")];
var r10 = row[hindex(data[0],"r10")];
var r11 = row[hindex(data[0],"r11")];
var r12 = row[hindex(data[0],"r12")];
var r13 = row[hindex(data[0],"r13")];
var q1 = row[hindex(data[0],"q1")];
var r14 = row[hindex(data[0],"r14")];
var q2 = row[hindex(data[0],"q2")];
var q3 = row[hindex(data[0],"q3")];
var q4 = row[hindex(data[0],"q4")];
var q5 = row[hindex(data[0],"q5")];
var r15 = row[hindex(data[0],"r15")];
var q6 = row[hindex(data[0],"q6")];
var r16 = row[hindex(data[0],"r16")];
var q7 = row[hindex(data[0],"q7")];
message = htmlcode.replace(/\{\{r1\}\}/,r1)
.replace(/\{\{r2\}\}/,r2)
.replace(/\{\{r3\}\}/,r3)
.replace(/\{\{r4\}\}/,r4)
.replace(/\{\{r5\}\}/,r5)
.replace(/\{\{r6\}\}/,r6)
.replace(/\{\{r7\}\}/,r7)
.replace(/\{\{r8\}\}/,r8)
.replace(/\{\{r9\}\}/,r9)
.replace(/\{\{r10\}\}/,r10)
.replace(/\{\{r11\}\}/,r11)
.replace(/\{\{r12\}\}/,r12)
.replace(/\{\{r13\}\}/,r13)
.replace(/\{\{r14\}\}/,r14)
.replace(/\{\{r15\}\}/,r15)
.replace(/\{\{r16\}\}/,r16)
.replace(/\{\{q1\}\}/,q1)
.replace(/\{\{q2\}\}/,q2)
.replace(/\{\{q3\}\}/,q3)
.replace(/\{\{q4\}\}/,q4)
.replace(/\{\{q5\}\}/,q5)
.replace(/\{\{q6\}\}/,q6)
.replace(/\{\{q7\}\}/,q7)
.replace(/\{\{name\}\}/,name);
*/
htmlsheet.getRange(1, 1).setValue(message);
htmlsheet.getRange(1, 2).setValue(JSON.stringify(obj));
if (confirm == "Yes" && EmailSent != "Email Sent") {
MailApp.sendEmail(emailAddress,subject, "", {
htmlBody: message,
replyTo: replyTo,
name: name_shown
});
sheet.getRange(startRow + i, 5).setValue("Email Sent");
}
}
}
Add cc:
The cc is an advanced parameter at sendEmail(recipient, subject, body, options), like htmlBody or replyTo. Therefore, when using sendEmail, you should add it this way:
MailApp.sendEmail(emailAddress,subject, "", {
htmlBody: message,
replyTo: replyTo,
name: name_shown,
cc: "YOUR_DESIRED_CC_EMAIL"
});
Use onFormSubmit:
There are two types of onFormSubmit triggers, one for the spreadsheet linked to the Form and the other for the Form itself. Depending on which one you install (see Installable Triggers for more information on how to install a trigger), you'd retrieve the value of a response in different ways, using the corresponding event object.
It's probably easier to get this information via the Sheets event object, so I'd suggest you to use the Sheets trigger. In this case, the event object has a field namedValues, which refers to an object containing the question names and values from the form submission. In the function triggered by the form submission, just find the key that corresponds to the item you want to fetch the response from, and retrieve its value. For example:
function triggeredByFormSubmit(e) {
const submittedColor = e.namedValues["Which colour do you like?"];
// ...
}
If you installed a Form's onFormSubmit instead, you should find the item response via the event property response, which corresponds to the FormResponse.
Note: Please note that this is supposed to run automatically when a user submits a form. If you try to execute it directly from the editor, or from the custom menu, it will fail because the event object (in the sample above, e) won't be defined.
Need Help to create a watchdog. I'm importing a webpage with some data. and want constantly check if imported data is the same whats my reference.
So I want the script to constantly compare 2 cells and if values became different, send me (the author) the email.
Want to compare H4 and E4
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Pricechecker");
var checkprice = sheet.getRange(E2:E2);
var currentprice = sheet.getRange(H4:H4);
if (currentprice <= checkprice) {
var emailAddress = "email#example.ge";
var message = "Discount";
var subject = "There is a Discount on your item";
MailApp.sendEmail(emailAddress, subject, message);
}
}
Solution:
You would need an Installable Trigger to automatically send email upon comparison of E4 and H4.
function createSpreadsheetEditTrigger() {
var ss = SpreadsheetApp.getActive();
ScriptApp.newTrigger('compare')
.forSpreadsheet(ss)
.onEdit()
.create();
}
function compare(e) {
if (e.range == "E4" || "H4") {
var sheet = SpreadsheetApp.getActiveSheet();
var checkPrice = sheet.getRange("E4").getValue();
var currentPrice = sheet.getRange("H4").getValue();
if (currentPrice <= checkPrice) {
var emailAddress = "email#example.ge";
var message = "Discount";
var subject = "There is a Discount on your item";
MailApp.sendEmail(emailAddress, subject, message);
}
}
}
Note that you only have to run createSpreadsheetEditTrigger() in Apps Script. The created trigger will run compare() everytime you make an edit to the spreadsheet. It will automatically check E4 and H4 and send email whether the condition is satisfied.
Console Output:
I have created a function that will allow me to send emails to a list of contacts via Google Sheets. The email will include a subject line and a table containing the data from my spreadsheet. The problem i am facing is that the HTML table is only sending the headers and 1 row of data. I can't find the error i have made.
The table will be ever increasing so i would like to email function to include all cells that have data in it. Is this possible?
I have adapted this Script/HTML code from How to format email from spreadsheet data using arrays? but i am now stuck with how to amend it further for my needs.
function testMail(){
var emails = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Contacts");
var startRow = 2; // First row of data to process
var numRows = 2; // Number of rows to process
// Fetch the range of cells A1:B1
var dataRange = emails.getRange(startRow, 1, numRows, 1);
// 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 subject = "Current list of BGC 4 Acronyms";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var acronym = ss.getSheetByName("Sheet1");
var abbv = acronym.getRange("A5:A50").getValues();
var explan = acronym.getRange("B5:B50").getValues();
var message = composeMessage(abbv,explan);
var messageHTML = composeHtmlMsg(abbv,explan);
Logger.log(messageHTML);
MailApp.sendEmail(emailAddress, subject, message, {'htmlBody':messageHTML});
}
function composeMessage(abbv,explan){
var message = 'Here are the data you submitted :\n'
for(var c=0;c<explan[0].length;++c){
message+='\n'+abbv[0][c]+' : '+explan[0][c]
}
return message;
}
function composeHtmlMsg(abbv,explan){
var message = '<br><br><table style="background-color:lightblue;border-collapse:collapse;" border = 1 cellpadding = 5><th>Acronym</th><th>Explanation</th><tr>'
for(var c=0;c<explan[0].length;++c){
message+='<tr><td>'+abbv[0][c]+'</td><td>'+explan[0][c]+'</td></tr>'
}
return message+'</table>';
}
The expected result is an email sent to each address in the list with a subject line and full table of data. What i am actually getting is this
Try changing this:
for(var c=0;c<explan[0].length;++c){
message+='\n'+abbv[0][c]+' : '+explan[0][c]
}
To this:
I assume that abbv and explan are columns.
for(var c=0;c<explan.length;c++){
message+='<br />' + abbv[c][0]+ ' : ' + explan[c][0];
}
Try this:
function composeHtmlMsg(abbv,explan){
var message = '<br><br><table style="background-color:lightblue;border-collapse:collapse;" border = 1 cellpadding = 5><th>Acronym</th><th>Explanation</th><tr>'
for(var c=0;c<explan.length;c++){
message+='<tr><td>'+abbv[c][0]+'</td><td>'+explan[c][0]+'</td></tr>'
}
return message+='</table>';
}
Based upon your spreadsheet sample I think this could work:
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Sheet1');
var rg1=sh.getRange(5,1,sh.getLastRow()-4,1);
var rg2=sh.getRange(5,2,sh.getlastRow()-4,1);
var explan=rg1.getValues();
var abbv=rg2.getValues();
I have been looking how to write the script to check and run on multiple tabs. What I have now, I would need to copy/paste and set execution triggers one by one.
Script I have:
function SendEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("1");
var value = sheet.getRange("F3").getValue();
var subject = "subject";
var message = "message";
if (value >0){
MailApp.sendEmail("email", subject, message);
}
}
I have this running every 8 hours (trigger run).
I am looking to add more tabs so that for each tab the script can check and send an email if the value of individual tabs is more than 0.
Any ideas on how to do this?
The value in every tab is under F3. Tab names, for example, 1,2,3,4...
Thank you!!!
This should do what you looking for if I understood the issue correctly.
function SendEmail() {
//Get the Spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
//Get all Sheets in the Spreadsheet
var sheets = ss.getSheets();
//Create a variable for the email address, subject and message
var email = "";
var subject = "";
var message = "";
//Can change the starting sheet by changing the value of "i" - 0 will be the first sheet.
for (var i = 0; i < sheets.length; i++){
var sheet = sheets[i];
var value = sheet.getRange("F3").getValue();
switch(sheet.getSheetName) {
case "Sheet1":
email = "email1#domain.com";
break;
case "Sheet2":
email = "email2#domain.com";
break;
default:
value = 1
email = "yourEmailAddress#domain.com";
subject = "Message Failed to Send";
message = "There was an error sending email, please investigate";
}
if (value >0){
MailApp.sendEmail(email, subject, message);
}//END OF IF STATEMENT
}//END OF FOR LOOP
}//END OF FUNCTION
I'm getting this error while running this sheet.
Cell reference out of range (line 81, file "genreportSE")
I don't know why it says it's 'out of range'.
I tried to used 'copyvalues'. I saw a script where you can't really "print" a range, but you can create another spreadsheet, copy that range, then print that sheet and delete it.
How should I accomplish this?
function genreportSE() { // This function let us read the value of a cell from a sheet and change the value of another cell in a different sheet
var ss = SpreadsheetApp.getActive(); //ss stands for spreadsheet, this is the active spreadsheet
var clientsheet = ss.getSheetByName('Clientes SE');
var gensheet = ss.getSheetByName('Generador SE');
var clienttable = clientsheet.getDataRange();
var numberofservices = clienttable.getNumRows(); //The number of services in the Clientes sheet
var error1;
var error2;
var rangetocheck1;
var rangetocheck2;
var client;
var clientname;
var i=0;
var reportswitherrors = []; //Array for faulty reports
var email ='jvaldez#galt.mx';
var subject = "Reporte de producción y consumo - " + (new Date()).toString();
var body = "TEXT" ;
for (i=0;i<=2;i++){
gensheet.getRange('B2').setValue(clientsheet.getRange(i+2,1).getValue()); //This will change the cell "B2" in "Generador SE" to the current service number for the report generation
Utilities.sleep(3000); //A timer to let the importdata function get the data from the SE server in miliseconds
client = gensheet.getRange('B4').getValue;
clientname = String(client);
rangetocheck1 = gensheet.getRange('B8:C14').getValues(); //Data range that could present calculation errors ********
rangetocheck2 = gensheet.getRange('H8:H14').getValues(); //Data range that could present calculation errors ********
if(String(rangetocheck1).indexOf('#N/A') == -1) { //This checks if there are any errors in rangetocheck1
error1 = false;
} else {
error1 = true;
};
if(String(rangetocheck2).indexOf('#N/A') == -1) { //This checks if there are any errors in rangetocheck2
error2 = false;
} else{
error2 = true;
};
if(error1||error2){
reportswitherrors.push(clientsheet.getRange(i+2,1).getValue()); //This appends the current service number to the faulty services array
} else {
// Convert individual worksheets to PDF
var newSpreadsheet = SpreadsheetApp.create("Spreadsheet to export",15,60);
newSpreadsheet.getSheetByName('Sheet1').activate();
var newsheet = newSpreadsheet.getSheetByName('Sheet1');
var genRange = gensheet.getRange('A1:H50').copyValuesToRange(newsheet,0,10,0,55)
var pdf = DriveApp.getFileById(newSpreadsheet.getId()).getAs('application/pdf').getBytes();
var attach = {fileName:'Weekly Status.pdf',content:pdf, mimeType:'application/pdf'};
MailApp.sendEmail(email, subject, body, {attachments:[attach]});
DriveApp.getFileById(newSpreadsheet.getId()).setTrashed(true);
}
};
Logger.log(reportswitherrors);
}
It appears that you've got your row & column dimensions flipped between function calls. (Because Google decided to be inconsistent with the order of them...)
This line calls create(name, rows, columns):
var newSpreadsheet = SpreadsheetApp.create("Spreadsheet to export",15,60);
You've created a spreadsheet with 15 rows and 60 columns.
A bit further along, probably on line 81, copyValuesToRange(sheet, column, columnEnd, row, rowEnd) gets invoked:
var genRange = gensheet.getRange('A1:H50').copyValuesToRange(newsheet,0,10,0,55)