Issue with static cc on Google's MailApp Script - javascript

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!

Related

Populate email subject line with form entries in Google Scripts

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});

Google Sheets keeps sending emails

Been building a landing page to start an email list. Decided to use Google Sheets as the backend to store emails & Google Scripts to send the first welcome message.
I hooked up an HTML page to Google Sheets with an API. The user submits their name & email, and then it goes to the Google Sheets. When the document is edited, this function gets triggered which sends a welcome message.
To prevent duplicate messages from going out, I put a simple system in place. When a user has been emailed, the third row (C) is filled in with "EMAIL_SENT" automatically.
When the function is triggered, it should only send the user an email if if there is no "EMAIL_SENT" but every time a new user submits their info, every single email on the list gets another welcome message.
I will attach an image of the spreadsheet
// This constant is written in column C 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 = sheet.getLastRow();
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 3);
// 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[0]; // First column
var nameThisMan = row[1]; // Person's name
var emailSent = row[2]; // Third column
if (emailSent !== EMAIL_SENT) { // Prevents sending duplicates
var message = "Hey there " + nameThisMan + "," + "\n \n Thanks for joining the email list! You’re about to be getting some AMAZING programming resources. Here’s the link to the top 10 open source Github repos PDF. \n https://www.dropbox.com/s/wm8ctsdojlsoss6/10%20Most%20Useful%20Open%20Source%20Repos%20for%20Developers.pdf?dl=0\n\n And here’s the link to the archive of all the resources from this email list. These are from all past emails. \n https://docs.google.com/document/d/1hWmGNYkn0czRI29JJu9HgUVC6L4AsNYBxwt45ABnT6w/edit?usp=sharing \n \n Thank you again for joining the list! I will do my best to give you absolutely amazing programming resources. \n \n best, \n Michael Macaulay, Techtime.";
var replyTo = "TechTimeDev#gmail.com";
var subject = "Welcome to TechTime's Email List";
MailApp.sendEmail(emailAddress, replyTo, subject, message);
sheet.getRange(startRow + i, 3).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
function sendEmails2() {
var sheet=SpreadsheetApp.getActiveSheet();
var startRow=2;
var numRows=sheet.getLastRow()-startRow+1;
var dataRange=sheet.getRange(startRow, 1, numRows, 3);
var data=dataRange.getValues();
for (var i=0; i < data.length; ++i) {
var row=data[i];
var emailAddress=row[0];
var nameThisMan=row[1];
var emailSent=row[2];
var replyTo="TechTimeDev#gmail.com";
var subject="Welcome to TechTime's Email List";
if (emailSent!='EMAIL_SENT') {
var message="Hey there " + nameThisMan + "," + "\n \n Thanks for joining the email list! You’re about to be getting some AMAZING programming resources. Here’s the link to the top 10 open source Github repos PDF. \n https://www.dropbox.com/s/wm8ctsdojlsoss6/10%20Most%20Useful%20Open%20Source%20Repos%20for%20Developers.pdf?dl=0\n\n And here’s the link to the archive of all the resources from this email list. These are from all past emails. \n https://docs.google.com/document/d/1hWmGNYkn0czRI29JJu9HgUVC6L4AsNYBxwt45ABnT6w/edit?usp=sharing \n \n Thank you again for joining the list! I will do my best to give you absolutely amazing programming resources. \n \n best, \n Michael Macaulay, Techtime.";
MailApp.sendEmail(emailAddress, replyTo, subject, message);
sheet.getRange(startRow + i, 3).setValue('EMAIL_SENT');
}
}
}
The method getLastRow() will return you the index of the last row with content. In the example you have provided this would be 3. However, what you actually want for performing getRange() is the number of rows you need to take. If you use three you would be taking an extra empty row and therefore, you would be getting the wrong values.
To change this to get the number of rows you need, you can simply do:
var numrows = sheet.getLastRow() - 1; instead of var numRows = sheet.getLastRow();
as you need to subtract from the index the number of rows you are not wanting to get in your range (in your case as you are ignoring the first row only 1 needs to be subtracted).

Google Script to automatically draft emails

My goal is to create email drafts automatically from a Google Sheets list. Everything works mostly, the only problem I am having is that the message in the email just says [object Object].
The subject is fine, the email address is fine, and the break to keep it from sending to the same person again is fine.
I am not sure what is wrong.... but I am guessing it starts at //Build the email message.
Any suggestions?
I have the following:
var EMAIL_DRAFTED = "EMAIL DRAFTED";
function draftPastDueEmails() {
var sheet = SpreadsheetApp.getActiveSheet(); // Use data from the active sheet
var startRow = 2; // First row of data to process
var numRows = sheet.getLastRow() - 1; // Number of rows to process
var lastColumn = sheet.getLastColumn(); // Last column
var dataRange = sheet.getRange(startRow, 1, numRows, lastColumn) // Fetch the data range of the active sheet
var data = dataRange.getValues(); // Fetch values for each row in the range
// Work through each row in the spreadsheet
for (var i = 0; i < data.length; ++i) {
var row = data[i];
// Assign each row a variable
var clientName = row[12]; // Client name
var clientEmail = row[14]; // Client email
var reference = row[1]; // Account Reference
var invNum = row[0]; // Invoice number
var emailStatus = row[20]; // Email Status
// Prevent from drafing duplicates and from drafting emails without a recipient
if (emailStatus !== EMAIL_DRAFTED && clientEmail) {
// Build the email message
var emailBody = '<p>Hello ' +clientName+ ',</p>';
emailBody += '<p>I hope all is well.</p>';
emailBody += '<p>I noticed that invoice <strong>' +invNum+ '</strong> is currently past due.</p>';
emailBody += '<p>Could you please take a moment to check your records to see if a payment has been made and provide a receipt to allow me to track it in my system.</p>';
emailBody += '<p>If no payment has been made for whatever reason, please do so as soon as possible so I can post it to your account.</p>';
emailBody += '<p>Please let me know if you have any questions.</p>';
emailBody += '<p>Best,</p>';
// Create the email draft
GmailApp.createDraft(
clientEmail, // Recipient
'Past due account - '+reference+ // Subject
'',
{
htmlBody: emailBody // Options: Body (HTML)
}
);
sheet.getRange(startRow + i, lastColumn).setValue(EMAIL_DRAFTED); // Update the last column with "EMAIL_DRAFTED"
SpreadsheetApp.flush(); // Make sure the last cell is updated right away
}
}
}
It looks like the problem is here:
// Create the email draft
GmailApp.createDraft(
clientEmail, // Recipient
'Past due account - '+reference+ // Subject
'',
{
htmlBody: emailBody // Options: Body (HTML)
}
);
The method is expecting 3 strings -- a recipient, subject and a body -- followed by options with your "htmlBody" parameter. The code above only provides a recipient and a subject. Try this instead:
// Create the email draft
GmailApp.createDraft(
clientEmail, // Recipient
'Past due account - '+reference, // Subject
'', // Plaintext body
{
htmlBody: emailBody // Options: Body (HTML)
}
);

In using this tutorial script from: https://developers.google.com/apps-script/articles/sending_emails can message column be changed dynamically?

In using this tutorial script from: https://developers.google.com/apps-script/articles/sending_emails
I am new to apps script and have been searching the forums trying to figure this out...
I'm trying to use another column in the spreadsheet to dynamically enter the salutation in the message. I thought it would be a formula like this:
="Dear "E2, + "Our 2018 Catalog is Coming Soon! Would you like a copy? " But, then I get the error that -ADD parameter1 is text and it is looking for numbers-, (even though I found it in another help area to use the quotes to separate the cell references).
So my questions:
1.Is it possible to make dynamic changes to the message in this script? Or do I need another script in the message column to do this?
2.If I am running more than one script on the spreadsheet and connected form do I need separate script files or just separate blocks on the same file
Thank you!
Adding a separate salutation to an email script
Here's the script for that tutorial:
// This constant is written in column C for rows for which an email
// has been sent successfully.
var EMAIL_SENT = "EMAIL_SENT";
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSheet();
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, 3)
// 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[0]; // First column
var message = row[1]; // Second column
var emailSent = row[2]; // Third column
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
var subject = "Sending emails from a Spreadsheet";
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 3).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
I believe you wish to have a separate salutation which is at the beginning of the message portion. It appears that you also wish to use column 5 for that data.
So if that's the case then your message would be something like this:
var message = Utilities.formatString('Dear %s\n%s',row[4],row[1]); Reference
This could also be accomplished this way:
var message = 'Dear ' + row[4] + '\n' + row[1];Reference
In either case you would put a name in column 5 and the rest of your message in column2. If you wan't to use html in your email replace the '\n' (line feed) with '<br />' (line break);
The message starts with the saluation in row[4] (column 5) and the rest of the message comes from row[1] according to the tutorial which is column 2.
The data from a getValues() command is returned in an array. Arrays index from zero where as columns in the spreadsheet begin at 1. Reference
If I misinterpreted your question please ask for further assistance in comments below. I'll be glad to help you.

Sent email notification if a change happens on specified columns on a google sheet

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

Categories