Modifying the Google Spreadsheet script for sending values by email - google-apps-script

This is an offshoot of a similar post here. A good answer was provided by Rivero but his code sends the values on the Google Spreadsheet's response sheet. I was wondering if instead the script would return values of the same row and column range specified by the code BUT from other sheet in the same spreadsheet. I'm really new to this and can't seem to find the right combination of codes to do so. Here is Rivero's code, I hope someone can help me accomplish this. Thanks in advance!
/* Send Confirmation Email with Google Forms */
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
for (var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendConfirmationMail")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendConfirmationMail(e) {
try {
var ss, cc, sendername, subject, columns;
var header, message, value, textbody, sender, itemID, url;
// This is your email address and you will be in the CC
cc = "name#email.com";
// This will show up as the sender's name
sendername = "name to be displayed as sender";
// Optional but change the following variable
// to have a custom subject for Google Docs emails
subject = "Choose an approppiate subject";
// This is the body of the auto-reply
message = "";
ss = SpreadsheetApp.getActiveSheet();
columns = ss.getRange(1, 1, 1, ss.getLastColumn()).getValues()[0];
// This is the submitter's email address
sender = e.namedValues["Username"].toString();
// Only include form values that are not blank
for ( var keys in columns ) {
var key = columns[keys];
//Use this to look for a particular named key
if ( e.namedValues[key] ) {
if ( key == "Username" ) {
header = "The user " + e.namedValues[key] + " has submitted the form, please review the following information.<br />";
} else {
message += key + ' ::<br /> '+ e.namedValues[key] + "<br />";
}
}
}
}
textbody = header + message;
textbody = textbody.replace("<br>", "\n");
Logger.log("Sending email");
GmailApp.sendEmail(cc, subject, textbody,
{cc: cc, name: sendername, htmlBody: textbody});
} catch (e) {
Logger.log(e.toString());
}
}

It would better if you can name your sheet and use it instead of using active spreadsheet.
var sheet = SpreadsheetApp.openById('spreadsheetId').getSheetByName('name');
OR you can also use the sheet number to access it.
var sheet = SpreadsheetApp.openById('spreadsheetId').getSheets()[0];
After you have reference to the sheet, get the range for the column followed by data array:
var columnRange = sheet.getRange('a1Notation');
var dataArray = columnRange.getValues();
then iterating the data as per your convenience
for(var i=1; i<=dataArray.length; i++)
{
}

Related

cell reference out of range on Email Notifications

I have the below code for sending a email notification when a cell changes, but it is always returning Cell reference out of range(line 5, file "Missing Cuts Report"). Can anyone advise if i need to change the code or if there is a way of getting it to stop failing and still send the email notification through. The trigger i use is OnChange because when it was on OnEdit it came back with error service invoked too many times on line 17 MailApp.sendEmail(recipients, subject, msgPlain, { htmlBody: body }). Any help would really be appreciated.
function sendEnailNotification(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cell = ss.getActiveCell().getA1Notation();
var cellvalue = ss.getActiveCell().getValue().toString();
if(SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName() == "Missing Cuts Report") {
if(cell.indexOf('B')!=-1){
if(cellvalue > "") {
//Define Notification Details
var recipients = "email#email.co.uk;
var subject = "New Missing Cut Added";
var body = 'A new line has been added on the Missing Cuts Report on line <b>' + cell + '</b> - click here to view the update';
var msgPlain = body.replace(/(<([^>]+)>)/ig, ""); // clear html tags for plain mail
MailApp.sendEmail(recipients, subject, msgPlain, { htmlBody: body });
}
}
}
}
Hi this is a not a very good way of achieving the result you want. Not really to sure what you are after. I have however made some adjustments to your code with notes after the closing braces. This is not an answer to your original problem. Just some hints.
function sendEmailNotification() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cell = ss.getActiveCell().getA1Notation();
var cellvalue = ss.getActiveCell().getValue().toString();
if(sheet.getName() === "Missing Cuts Report") {
//if(cell.indexOf('B')!== -1){
if(cellvalue !== "") {
//Define Notification Details
var recipients = "email#address.org";
var subject = "New Missing Cut Added";
var body = 'A new line has been added on the Missing Cuts Report on line <b>' + cell + '</b> - click here to view the update';
var msgPlain = body.replace(/(<([^>]+)>)/ig, ""); // clear html tags for plain mail
MailApp.sendEmail(recipients, subject, msgPlain, { htmlBody: body });
} // "<" and ">" are not for comparing string values. (At least not in this case.)
//} //IndexOf will always result in -1 if you are looking for just "B" as your result will always be "B1/B2/B3/ect."
} // Already have the sheet object, no need to call again.
}

Row number of a variable in Spreadsheet (Apps Script)

In my Spreadsheet, I have taken the answers from the users and added a column to grade them. Now, I want to mail them the whole data they have entered and their respective grades. To do that, I have to know the Row number of the variable "key2" which will be changing for every response of the user. I am providing my code here. Some one please help me.
/* Send Confirmation Email with Google Forms */
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
for (var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendConfirmationMail")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendConfirmationMail(e) {
var s1 = SpreadsheetApp.getActiveSpreadsheet();
var s2 = SpreadsheetApp.setActiveSheet(s1.getSheetByName("Sheet2"));
try {
var cc, sendername, subject, column2;
var message, value, textbody, sender;
// This is your email address and you will be in the CC
cc = Session.getActiveUser().getEmail();
// This will show up as the sender's name
sendername = "Quiz2win";
// Optional but change the following variable
// to have a custom subject for Google Docs emails
subject = "Google Form Successfully Submitted";
// This is the body of the auto-reply
message += "We have received your details.<br />Thanks!<br /><br />";
column2 = s2.getRange(1,1,1,10).getValues()[0];
// This is the submitter's email address
sender = e.namedValues["Email Address"].toString();
// Only include form values that are not blank
for ( var keys in column2 ) {
var key2 = column2[keys];
if ( e.namedValues[key2] ) {
message += key2 + ' :: '+ e.namedValues[key2] + "<br />";
} else {
var key1 = s2.getValues();
message += key2 + ' :: ' + key1 + "<br/>";
}
}
textbody = message.replace("<br>", "\n");
GmailApp.sendEmail(sender, subject, textbody,
{cc: cc, name: sendername, htmlBody: message});
} catch (e) {
Logger.log(e.toString());
}
The range you are mentioning here s2.getRange(1,1,1,10) is basically getting only first row of data from the sheet.
Instead get all the rows and column values into a range variable and loop through the range for each row and send an email in the loop itself.
Check this documentation for more details.

Send email to specific user based on Google Form

Background: Google Script for Forms creating a phone message log that emails to a specific person as selected.
Need help with the email address portion of the code. I want to have a message sent to an email address based on the radio button with the person's name selected.
function Initialize() {
var triggers = ScriptApp.getScriptTriggers();
for (var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendGoogleForm")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendGoogleForm(e) {
try {
var email = HELPHELPHELP;
// Optional but change the following variable
// to have a custom subject for Google Form email notifications
var subject = "Google Docs Form Submitted";
var s = SpreadsheetApp.getActiveSheet();
var columns = s.getRange(1, 1, 1, s.getLastColumn()).getValues()[0];
var message = "";
// Only include form fields that are not blank
for (var keys in columns) {
var key = columns[keys];
if (e.namedValues[key] && (e.namedValues[key] != "")) {
message += key + ' :: ' + e.namedValues[key] + "\n\n";
}
}
// This is the MailApp service of Google Apps Script
// that sends the email. You can also use GmailApp for HTML Mail.
MailApp.sendEmail(email, subject, message);
} catch (e) {
Logger.log(e.toString());
}
}
Presumably the intended recipient's name comes from a question / column with a title like "Message for".
In that case, try this:
...
var email = resolveEmail( e.namedValues["Message for"] );
...
function resolveEmail( userName ) {
// List of userNames & (secret) email addresses
var userEmails = {
"Mickey" : "bigears#example.com",
"Donald" : "duckman#example.com" // etc.
};
if (userName in userEmails) {
return userEmails[userName];
}
else {
// Unknown user - send email to script owner
return Session.getEffectiveUser().getEmail();
// Alternatively, could throw an error to get notified
// throw new Error( "Could not resolve email for user: " + userName );
}
}

How can i send confirmation mail send different from address?

I'm sending confirmation mail with following code in google docs scripts.
But It is sending from my personal gmail address. I need define different mail address. Cause I will use this for my company and mail need show like that sometest#companytsite.com
How can i do that?
My Code:
function Initialize() {
var triggers = ScriptApp.getScriptTriggers();
for (var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendConfirmationMail")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendConfirmationMail(e) {
try {
var ss, cc, sendername, subject, columns;
var message, value, textbody, sender;
// This is your email address and you will be in the CC
cc = Session.getActiveUser().getEmail();
// This will show up as the sender's name
sendername = "Your Name Goes Here";
// Optional but change the following variable
// to have a custom subject for Google Docs emails
subject = "Google Form Successfully Submitted";
// This is the body of the auto-reply
message = "We have received your details.<br>Thanks!<br><br>";
ss = SpreadsheetApp.getActiveSheet();
columns = ss.getRange(1, 1, 1, ss.getLastColumn()).getValues()[0];
// This is the submitter's email address
sender = e.namedValues["Email Address"].toString();
// Only include form values that are not blank
for ( var keys in columns ) {
var key = columns[keys];
if ( e.namedValues[key] ) {
message += key + ' :: '+ e.namedValues[key] + "<br />";
}
}
textbody = message.replace("<br>", "\n");
GmailApp.sendEmail(sender, subject, textbody,
{cc: cc, name: sendername, htmlBody: message});
} catch (e) {
Logger.log(e.toString());
}
}
According to the documentation: https://developers.google.com/apps-script/reference/gmail/gmail-app#sendEmail(String,String,String,Object)
You should be able to pass in a from in the options.
GmailApp.sendEmail(sender, subject, textbody, {
from: "sometest#companytsite.com",
cc: cc,
name: sendername,
htmlBody: message
});
Nb. to avoid confusion sender should really be to
Now it also says that the email address you want to send it from must be an alias, to check you can print out getAliases() to see if it exists. If not you should be able to follow these instructions:
https://support.google.com/mail/answer/22370?hl=en

Email Google Form Results not working

I am using a script to have form results e-mailed to me every time the form is submitted. Entire code is posted in Google Groups here:
http://groups.google.com/a/googleproductforums.com/d/topic/apps-script/1rObNfuez6k/discussion
Here's the current code:
function contactUsMailer2(e) {
// var ss = SpreadsheetApp.getActive();
// SpreadsheetApp.setActiveSpreadsheet(ss);
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data'); //default sheets - change if you
var setup = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Setup'); //rename the sheets
var width = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data').getLastColumn(); //get "width" of sheet, used to enumrate fields
var myEmailAddress = setup.getRange('B3').getValue(); //get email recipient(s) from "Setup" (default)
var myEmailSubject = setup.getRange('B4').getValue(); //get a subject line from "Setup" (default)
//from row 1 of "Data"
var sheetURL = SpreadsheetApp.getActiveSpreadsheet().getUrl(); //get sheet url to include in email
var formURL = SpreadsheetApp.getActiveSpreadsheet().getFormUrl(); //get form url to include in email
var column = 'A';
var message = '';
var htmlBody = '<html><body><table>'; //generated email will have both an HTML table and a plain-text part
//to be RFC compliant. beginning of html and table.
for (var c=1; c<=width; ++c) {
var data = sheet.getRange(1, c, 1, 1).getValue(); //this gets the "filed" names from the 1st row of "Sheet1"
try {
//retrieve field data and build the HTML and plain-text emails
var message = message + data + ': ' + e.namedValues[data].toString() + '\r\n'; //plain-text
var htmlBody = htmlBody + '<tr><td><b>' + data + ': </b></td><td>' + e.namedValues[data].toString() + '</td></tr>'; //HTML
}
catch (a) {
var message = message + data + ': n/a\r\n';
var htmlBody = htmlBody + '<tr><td><b>' + data + ': </b></td><td>n/a</td></tr>';
}
var column = String.fromCharCode(column.charCodeAt() + 1); //increment column letter
}
var htmlBody = htmlBody + '</table>'; //close table
var message = message + '\r\n\r\nData from form located at ' + formURL + '\r\n'; //put form url in text email
var message = message + 'Data posted to spreadsheet at ' + sheetURL; //put sheet url in text email
var htmlBody = htmlBody + '<br><br>Data from form located here<br>'; //put form url in HTML email
var htmlBody = htmlBody + 'Data posted to spreadsheet here<br>'; //put sheet url in HTML email
var htmlBody = htmlBody + '</body></html>'; //close html
MailApp.sendEmail(myEmailAddress, myEmailSubject, message, {htmlBody: htmlBody}) ; //send the email
}
function showid() {
Browser.msgBox("The sheet ID is:\r\n\r\n" + SpreadsheetApp.getActiveSpreadsheet().getId());
}
Script now works fine with the original spreadsheet, but when I try to use it with a new form and spreadsheet it fails to send the e-mail. The form fill in the spreadsheet just fine and we get the usual e-mail stating that the spreadsheet has been updated, but the script e-mail doesn't come through.
Funny thing is when I debug the script it does send the e-mail, just null entries in all fields (which is what I would expect). Debug doesn't report any errors in the script itself. What am I missing?
Have you authorized the script in your new form ? Since your script is required to send out an email it requires explicit authorization.
Try removing the quote around
for (var c=1; c<=width; ++c) {
var data = sheet.getRange(column + '1').getValue(); //this gets the "filed" names from the 1st row of "Sheet1"
I do something similar in a script and the following works for me.
var rangeval = "B"+(i+1);
var nameFld = filesheet.getRange(i+1,1).getValue();
Joe
Make sure trigger is set to "On Submit". Mine was set to "On Open".