I'm writing a script for a google spreadsheet that should check to see whether the value of a particular cell is "Yes." If so, it should just end. If not, it should send an e-mail with the contents of several other cells to a defined address and write "Yes" to the designated cell. However, the if condition in the code seems to always evaluate as true even when it should evaluate as false. The script writes "Yes" to the designated cell and sends the e-mail. However, while the e-mail contains the contents of the designated cells, it's all out of order. Here's the script:
function sendNotification() {
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange(2,1,1,6);
var data = dataRange.getValues();
var dateSubmitted = data[0];
var dateDue = data[1];
var url = data[2];
var currentText = data[3];
var newText = data[4];
var emailSent = data[5];
var test = 'Yes';
var emailAddress = 'harland.westgate#gmail.com';
var message = 'On ' + dateSubmitted + ' a colleague requested that ' + url + ' be changed to replace the text ' + currentText + ' with ' + newText + '. This change should be completed by ' + dateDue;
var subject = 'A website change has been requested';
if (emailSent!=test) { // Prevents sending duplicates
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(2,6).setValue(test);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
The relevant cells are (sorry, tried to screenshot but rep is too low):
A2: 1/11/14
B2: 1/17/14
C2: www.google.com
D2: Lorem ipsum
E2: Dolor sit amit
F2: Yes
here's what it dumps into the body of the e-mail:
On Sat Jan 11 2014 00:00:00 GMT-0500 (EST),Fri Jan 17 2014 00:00:00 GMT-0500 (EST),www.google.com,Lorem ipsum,Dolor sit amit,Yes a colleague requested that undefined be changed to replace the text undefined with undefined. This change should be completed by undefined
I've searched extensively and have not found an explanation for either behavior. I don't think it's that the script is failing to read in the values of the cell range, because the e-mail body contains those values (just not where I was expecting them). Then again, in the places I was expecting those values, it drops in "undefined."
Remember getValues() returns a two-dimensional array of values.
Try:
...
var dateSubmitted = data[0][0];
var dateDue = data[0][1];
var url = data[0][2];
...
Related
I am completely new to Google Scripts. I experimented with the script found here (as written by Snipe and edited by Govoni in the first comment).
What I am trying to do is combine both scripts, to get an email on form submit that would:
only show answered questions (it works)
format questions in bold (it works)
populate the subject line (I can't get it to work)
The code below works.
function newResponse()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var formName = ss.getSheetByName('Form Responses 1');
var lastRow = formName.getLastRow();
var lastColumn = formName.getLastColumn();
var email = "sample#myemail.com";
var name = "My Email";
var subject = 'New form response: ';
var body = '';
var cell = '';
for (var i = 1; i <= lastColumn ; i++)
{
var title = formName.getRange(1,i).getDisplayValue();
var cell = formName.getRange(lastRow, i).getDisplayValue();
if (cell != '' && cell != 0)
{
body = body + '<b>'+ title + '</b>: ' + cell + '<br>';
};
};
MailApp.sendEmail({
to: email,
name: name,
subject: subject,
htmlBody: body
});
}
So, to try and add variable entries to the subject line I changed 'function newResponse()' to 'function newResponse(e)' and added this line before MailApp:sendEmail:
// The email subject line should look like this: "New form response: Item (Company, Country)"
// Item, Company and Country are the 2nd, 3rd and 4th columns from my form
subject += e.namedValues[title[1]].toString() + " (" + e.namedValues[title[2]].toString()+ ", "
+ e.namedValues[title[3]].toString()+ ")";
But when I do this, it doesn't send an email at all. If I change e.namedValues and instead put something like [title[0]], it then returns the first letter of the last question answered.
I am not quite sure what to try next?
From your code snippet, I suppose title variable holds a string, so title[0] is the first character of the string. e.namedValues[title[1]] will be undefined if no questions are single-character. undefined.toString() will throw an error, crashing the entire script.
You'll need to save an array of titles of all columns in the sheet.
var titles = [];
for (var i = 1; i <= lastColumn ; i++) {
var title = formName.getRange(1,i).getDisplayValue();
titles.push(title);
var cell = formName.getRange(lastRow, i).getDisplayValue();
...
}
Afterwards, you'll be able to use e.namedValues[titles[1]]. Note that I use titles, the array.
Subject is not a member of the advanced parameters object its just a mailapp.senEdmail parameter.
Try:
sendEmail(email, subject, '', {name: name, htmlBody: body});
Okay, so I'm working on a script that will basically pull information from a spreadsheet to then send out in an email once an email address is added into the spreadsheet. The issue is I'm trying to add a noReply and cc setting but it seems to then break my script to where it keeps sending emails or doesn't send any at all.
Theory: I think 'cc' is throwing the issue as the script is reading it as a recipient and just sending the email out instead of using the recipient that's added into the spreadsheet. This is the reference I'm following: https://developers.google.com/apps-script/reference/mail/mail-app#sendEmail(String,String,String,Object)
This is my code with the issue section being commented as such:
// This constant is written in column M for rows for which an email
// has been sent successfully.
var EMAIL_SENT = 'EMAIL_SENT';
/**
* Sends non-duplicate emails with data from the current spreadsheet.
*/
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 3; // Number of rows to process
// Fetch the range of cells
var dataRange = sheet.getRange(startRow, 1, numRows, 20);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[8]; // Column I
var message = ('For the ticket below, please ensure that you call the user as the first resort before following up via email.' + '\n\n TimeStamp: ' + row[1] + '\n Agent Name: ' + row[2] + '\n Your site: ' + row[3] + '\n Zendesk Link: ' + row[4] + '\n Summary of User Issue: ' + row[5] + '\n De-Escalation Attempted:' + row[6] + '\n User Contact Number ' + row[7]); // Fetch of columns B-H
var emailSent = row[12]; // Column M
if (emailSent !== EMAIL_SENT) { // Prevents sending duplicates and everything after && emailAddress is just testing a fix but didn't work
var subject = 'You have been assigned a Supervisor Call. Please Action Within 24 hours!';
MailApp.sendEmail(emailAddress, subject, message, { // Section below gives the issue
noReply: true,
cc: 'cc#email.com'
});
sheet.getRange(startRow + i, 13).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
Screenshot of spreadsheet layout:
enter image description here
This is my first time writing out a question on Stack but feel free to ask and I can detail more of what you need in order to help out.
I was able to get this working with Cooper's help. I had to do some small formatting changes to get it working but ultimately the code wasn't incorrect, just format issues that caused it to not be read appropriately.
Appreciate the help!
I am using a google spreadsheet which looks like:
A B C D
1 Name e-mail Identifer Status
2 Alex ax#gmail.com ERT ER A
3 Micke miike477#gmail.com Ejyu er w
4 John john7788#tri.com Arb Ed C
I have a drop down list in column D (let say A,B & C for example), now i want that whenever the value changes (Initially the column D would be blank) in column D against a particular Name than an automatic e-mail trigger to e-mail id mentioned in column B by below mentioned sender id and content.
The email should be trigger whenever value changes in column D except for the blank, and if there were previously value was "B" and now it change to "C" than mail should be trigger.
Sender-example#gmail.com
CC-test1#gmail.com,test2#gmail.com
E-mail Body:
Hi Alex (Should be picked from column A depending against which name e-mail trigger)
some sentence here.
some sentence here with your ERT ER (Should be pick from column C) has status A (should be pick from column D).
Regards,
example
123456789
I am trying using below mentioned script:
function onEdit(event){
if(event.range.getColumn() == 4){ //A -> 1, B -> 2, etc
function sendMyEmail(line){
var sendTo = spreadsheet.getRange(row, 2).getValue();
var cc = 'test1#gmail.com'+","+'test2#gmail.com';
var subject = "What is the: "+ spreadsheet.getRange(row, 3).getValue();
var content = "Hi "+spreadsheet.getRange(row, 1).getValue();+","
+"what is the vlaue "+spreadsheet.getRange(row, 3).getValue();+ "with the status"+spreadsheet.getRange(row, 4).getValue();+ "."
MailApp.sendEmail(sendTo,
cc,
subject,
content);
}
}
}
You have two major issues.
Simple triggers cannot access services that require authorization (such as MailApp).
Your usage of MailApp.sendEmail() is incorrect as you're passing cc to where should be passed either the subject or the replyTo address (docs). Argument order is important.
To address the issue of simple triggers, all you need to do is install a trigger manually that calls your function on edit.
All other issues are addressed in the code below.
function sendEmailToUser(event){
var eventRange = event.range;
var sheet = eventRange.getSheet();
var sheetName = sheet.getName();
var column = eventRange.getColumn();
if (sheetName == "Sheet1" && column == 4){ // Make sure the edited column is in the correct sheet, otherwise editing Column D in Sheet3 might trigger this
var row = eventRange.getRow(); // You need to know which row so you can send the email to the correct person
var rowValues = sheet.getRange(row, 1, 1, 4).getValues();
var name = rowValues[0][0];
var sendTo = rowValues[0][1];
var identifier = rowValues[0][2];
var status = rowValues[0][3];
if (status != "") { // Don't send the email if the status is blank
var cc = "test1#example.com, test2#example.com";
var subject = "What is the: " + identifier;
var content = "Hi " + name + "\nWhat is the value " + identifier + " with the status " + status + "?";
MailApp.sendEmail(sendTo, subject, content, {
cc: cc
});
}
}
}
I have a Spreadsheet in Google Drive, which has two sheet in it "Production" and "Germination"
For the Production sheet, I to an email notification if a change has been made to the columns from A - F. Also if there is a row added or delete from the sheet.
The following code does the trick to some extent:
function onEdit( e ){
//To get email notification if any changes to the perticular cells
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("production");
var cell = ss.getActiveCell().getA1Notation();
var row = sheet.getActiveRange().getRow();
var cellvalue = ss.getActiveCell().getValue().toString();
var recipients = "zeeshanrang#gmail.com";
var message = '';
if(cell.indexOf('C')!=-1){
message = sheet.getRange('D'+ sheet.getActiveCell().getRowIndex()).getValue()
}
var subject = 'Update to '+sheet.getName();
var body = sheet.getName() + ' has been updated. Visit ' + ss.getUrl() + ' to view the changes on row: «' + row + '». New comment: «' + cellvalue + '». For message: «' + message + '»';
Logger.log(body);
//MailApp.sendEmail(recipients, subject, body);
};
But it sends me a mail on every edit, which is not required. It's required to send mail once every hour (if there is a change). Also right now it is only checking for changes on only Column C and not the rest of them.
Also, I was unable to understand if(cell.indexOf('C')!=-1) . Can someone explain me what does this statement means.
TIA
It means the following:
if(cell.indexOf('C')!=-1) // means that if you edit column C
....... //the following will happen
}
So to explain in more detail:
cell.indexOf('C')-> search for 'C'
!= -> Does not equal
-1 -> not there/ not found
if(cell.indexOf('C')!=-1) -> if indexOf('C') does not equal '-1' (i.e. if 'C' is there, do the 'if' statement
I am using the enhanced workflow script that was posted by Mogsdad here.
I have managed to work out a few issues but one that I am stuck on at the moment is the error that comes up from this section -
// Record approval or rejection in spreadsheet
var row = ArrayLib.indexOf(data, 0, timestamp);
if (row < 0) throw new Error ("Request not available."); // Throw error if request was not found
sheet.getRange(row+1, approvalCol).setValue(e.parameter.approval);
I get the "Request not available" error because the ArrayLib.indexOf object is comparing the time stamp that is being presented from the same source but via two different 'routes'.
The timestamp from the 'timestamp' variable looks like this - "17/03/2015 18:00:11"
...and the timestamp contained in the 'data' variable (that should match the timestamp variable) looks like this - "Tue Mar 17 2015 00:30:10 GMT-0700 (PDT)".
I am assuming that the two different formats is what is resulting in the ArrayLib.indexOf object returning a '-1' result and hence the error message.
Any thoughts on what I need to do to get the matching working successfully ?
Create a new Date object for the timestamp value, so that you can ensure they can be compared. The code should look like:
var dateFromTimestamp = new Date(timestamp);
After looking around at a few other posts I came up with a solution that seems to work pretty well and overcomes the issues with using the timestamp.
I put an array formula in the first column of the response sheet that created a ticket number -
=ArrayFormula(if(B2:B,"AFR"&text(row(A2:A)-1,"00000"),iferror(1/0)))
Then I retrieved the ticket number (var cellVal) and sent it with the email. The response email brings the approval value to the correct line every time....so far.
function sendEmail(e) {
// Response columns: Timestamp Requester Email Item Cost
var email = e.namedValues["Requester Email"];
var item = e.namedValues["Item"];
var cost = e.namedValues["Cost"];
//var timestamp = e.namedValues["Timestamp"];
var row = e.range.getRow();
var seq = e.values[1];
var url = ScriptApp.getService().getUrl();
var sheet = SpreadsheetApp.openById('1pFL0CEW5foe8nAtk0ZwwTleYrBn2YulMu_eKPDEFQaw').getSheetByName("Form Responses 1");
var range = sheet.getDataRange();
var cellval = range.getCell(row,1).getValue();
//var origMail = range.getCell(row,3).getValue();
Logger.log(cellval);
//Logger.log(origMail);
var options = '?approval=%APPROVE%&reply=%EMAIL%'
.replace("%EMAIL%",e.namedValues["Requester Email"])
var approve = url+options.replace("%APPROVE%","Approved")+'&row='+row+'&cellval='+cellval;
var reject = url+options.replace("%APPROVE%","Rejected")+'&row='+row+'&cellval='+cellval;
var html = "<body>"+
"<h2>Please review</h2><br />"+
"Request from: " + email + "<br />"+
"Ticket No: " + cellval + "<br />"+
"For: "+item +", at a cost of: $" + cost + "<br /><br />"+
"Approve<br />"+
"Reject<br />"+
"</body>";
MailApp.sendEmail(Session.getEffectiveUser().getEmail(),
"Approval Request",
"Requires html",
{htmlBody: html});
}