Error on code: Sends emails to supposedly non-recipients - javascript

I have a code that sends an email to different recipients based on a google sheet. However, the code keeps on sending emails to the "owner" recipient, which I hope to stop. To explain further, please see below details.
Here's where people put in their email addresses, tasks, etc.:
These data are then processed in a hidden sheet that uses several array functions to consolidate tasks for similar emails:
Now, I'm currently using this code, which perfectly works, except for one flaw:
function sendEmails() {
var now = new Date().toLocaleDateString();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var startRow = 2;
var sheet = ss.getSheetByName ('Tasks')
var numRows = sheet.getRange("H1").getValue();
var dataRange = sheet.getRange(startRow, 1, numRows, sheet.getLastColumn());
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[0];
var message = row[1];
message = message.replace(/\n/g, "</li><li>");
var ReminderDate = row[2].toLocaleDateString();
var Status = row[4];
var subject = "Task reminders";
if (ReminderDate > now)
continue;
if (Status == 1) {
var Email = {
to: emailAddress,
subject: "Task reminders | "+now,
htmlBody:
"Good day! This is to remind you of the following specific task/s:"+
"<br />"+
"<ul><li>"+message+"</li></ul>"+
"<br />"+
"You can access the Task monitoring sheet by clicking here.",
name: "Taks monitoring",
};
MailApp.sendEmail(Email);
sheet.getRange(startRow + i, 4).setValue(now);
SpreadsheetApp.flush();
}
}
}
And here's what is happening:
Tasks for email2 are sent to email2 (Yes!)
Tasks for email1 and email2 are sent to email1 (Oh no!)
I don't like the second bullet from happening, since I only want what's email1 to be sent to email1. I've analyzed the code step-by-step, but I'm not really sure what's wrong in here as to why it keeps doing the second bullet. I tried entering a new email3, and the code also sends email3's tasks to email1.
Any ideas on why this is happening, and suggestions to prevent it?
Just to note: email1 owns the google sheet (I think it has something to do with that).

Related

Not working: Code to send email reminder based on date

Wazzup guys, thanks to this website, I was able to get a code that allows sending email reminders. Now, I wanted to send only reminders based on date, particularly when the Reminder date matches the date today. I found out this awesome post, but was still not able to make it work.
I tried several attempts to google similar cases, but to no avail. The code is actually working without the "based on date" condition, but I can't seem to work it out. I tried changing formats, used the "Utilities" in the script, but still nothing.
Below is how the sheet looks like and as well the code. So on the current data, I should be receiving an email reminder for the "Go to gym" task, but I don't get any (I've included my correct email in column A though).
Where could have this gone wrong? Hoping for your insights and guidance on this. Thanks!
var EMAIL_SENT = "Yes";
function sendEmails() {
var now = new Date().toLocaleDateString();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var startRow = 2;
var sheet = ss.getSheetByName ('Tasks')
var numRows = sheet.getLastRow();
var dataRange = sheet.getRange(startRow, 1, numRows, sheet.getLastColumn());
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[0];
var message = row[2];
var ReminderDate = row[3];
var emailSent = row[4];
var subject = "Task reminder: "+row[1];
if (ReminderDate != now)
continue;
if (emailSent != EMAIL_SENT) {
message = "Good day! This is to remind you of a spefic task: "+ message +". \n\nThis reminder was triggered by the task monitoroing sheet: "+ ss.getUrl()
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 5).setValue(now);
SpreadsheetApp.flush();
}
}
}
Issue:
At Spreadsheet, when the date is used, the value retrieved by getValue() and getValues() is the date object. In your script, when row[3] of var row = data[i] is the date object, if (ReminderDate != now) is always false.
Modified script:
In order to avoid above issue, please modify as follows, because now of if (ReminderDate != now) is var now = new Date().toLocaleDateString();.
From:
var ReminderDate = row[3];
To:
var ReminderDate = row[3].toLocaleDateString();
Reference:
toLocaleDateString()

Get Google Emailer Script To Run For A Specific Set of Tabs

I have an emailer script that I would like to run for specified tabs and also make sure it skips any rows with blank values as it currently seems to break down as soon as it hits a blank row.
I have successfully built the script to work for one tab, but it seems to break down as soon as I try and get it to work for multiple tabs.
function reminders() {
var ss = SpreadsheetApp.openById("SHEET-ID");
var sheet = SpreadsheetApp.setActiveSheet(ss.getSheetByName(("sheet_1","sheet_2","sheet_3")));
var editedCell = sheet.getActiveRange().getColumnIndex();
var dataRange = sheet.getDataRange();
var data = dataRange.getValues();
var text1 = 'Insert body of email here';
for (var i = 1; i < data.length; i++)
(function(val) {
var row = data[i];
var recipient = row[4];
var name = row[2];
var replyto = 'reply_to#email.com';
var body = 'Dear' + ' ' + name + ',' + '\n\n' + text1;
var subject = 'Hello World';
GmailApp.sendEmail(recipient, subject, body, {from:'reply_to#email.com', replyto:'reply_to#email.com'});
})(i);
}
This currently works for sheet_1 but does not work for sheet_2 or sheet_3.
Does anyone have any suggestions for how I can improve this script to send to multiple sheets and also skip blank rows?
You want to send emails using the values of column "C" and "E" from the Spreadsheet.
You want to run your script for the sheet names of "sheet_1", "sheet_2" and "sheet_3".
You want to skip the rows which have no values of the column "C" and/or "E".
If my understanding is correct, how about this modification?
Modification points:
It seems that when var sheet = SpreadsheetApp.setActiveSheet(ss.getSheetByName(("sheet_1","sheet_2","sheet_3"))); is run, only "sheet_3" is retrieved.
In your case, I think that setActiveSheet() might not be required to be used.
Number of arguments of getSheetByName(("sheet_1","sheet_2","sheet_3")) is one.
When you want to use multiple sheets, please use each sheet name in the loop.
var editedCell = sheet.getActiveRange().getColumnIndex(); is not used in your script.
val of (function(val) { is not used in your script.
When you want to skip the empty rows, please put the if statement before GmailApp.sendEmail(). By this, the error is removed at GmailApp.sendEmail().
When above points are reflected to your script, it becomes as follows. Please think of this as just one of several answers.
Modified script:
Please copy and paste the following modified script to the script editor.
function reminders() {
var sheets = ["sheet_1","sheet_2","sheet_3"]; // Please set the sheet names here.
var ss = SpreadsheetApp.openById("SHEET-ID");
for (var s = 0; s < sheets.length; s++) {
var sheet = ss.getSheetByName(sheets[s]);
var dataRange = sheet.getDataRange();
var data = dataRange.getValues();
var text1 = 'Insert body of email here';
for (var i = 1; i < data.length; i++) {
var row = data[i];
var recipient = row[4];
var name = row[2];
if (!recipient || !name) continue; // Here, the empty rows are skipped.
var replyto = 'reply_to#email.com';
var body = 'Dear' + ' ' + name + ',' + '\n\n' + text1;
var subject = 'Hello World';
GmailApp.sendEmail(recipient, subject, body, {from:'reply_to#email.com', replyto:'reply_to#email.com'});
}
}
}
Note:
In this modified script, when "recipient" or "name" are not existing, the row is skipped.
When you send a lot of emails, please be careful the quotas of "Email read/write". You can see it at here.
References:
getSheetByName(name)
Quotas for Google Services
If I misunderstood your question and this was not the result you want, I apologize.

Failed redundancy measures on google script for sending emails via google sheets

I'm trying to send a reminder for a weekly webinar with emails that live on a Google Sheet using Google's script editor/codelab. The link for the tutorial it's based off of is here: https://developers.google.com/apps-script/articles/sending_emails
In their second section of code they post, it is an improved version because after the email is sent it populates a column with "EMAIL_SENT" and should prevent a duplicate email being sent out because "EMAIL_SENT" occupies that space (as I understand it).
My problem is that after I run the script, I'm able to get the emails to send off (I used three email accounts and each one received it), but I also get an error that reads:
Failed to send email: no recipient (line 24, file "macros").
Macros is the name of the file. The other issue I'm having is that if I run the script again after EMAIL_SENT has populated, it still sends an additional email even though it's not supposed to.
I've tried making the object in the first portion of the code different numbers to try and capture the right data. After I got the right data in there I don't understand why the other portions won't work.
`// 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 sendEmails_w_verification() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 116; // First row of data to process
var numColumns = 8;
var startColumn = 1;
// Fetch the range of cells as object
var dataRange = sheet.getRange(startRow, startColumn,
sheet.getLastRow(), numColumns);
// 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[1]; // Second column
var message = "Thank you for registering for the webinar"; // Second
column
var emailSent = row[8]; // ninth column
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
var subject = 'AFWERX Webinar Reminder';
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 9).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is
interrupted
SpreadsheetApp.flush();
}
}
}
Expected duplicates not to send and no error message of "Failed to send email: no recipient (line 24, file "macros")" when the email sent.
Your first no recipient error seems to be caused by how you're starting your for loop, if you switch it to i++ instead, the script runs fine. This is because by using ++i you're picking up an extra row which doesn't have any email address in it, causing it to throw the "no recipient" error you're getting.
The second issue with the script not being able to check against column 9 is because the range you defined is only 8 columns wide, not 9. I found this by using a simple Logger.log(emailSent) which came back as undefined, which is what you'd expect to see if the value isn't even being defined in the range at all.
// 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 sendEmails_w_verification() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 1; // First row of data to process
var numColumns = 9;
var startColumn = 1;
// Fetch the range of cells as object
var dataRange = sheet.getRange(startRow, startColumn, sheet.getLastRow(), numColumns);
// 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[1]; // Second column
var message = "Thank you for registering for the webinar"; // Second column
var emailSent = row[8]; // ninth column
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
var subject = 'AFWERX Webinar Reminder';
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 9).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
I've changed the for statement to use i++ rather than ++i which fixes the "no recipient" error message.
for (var i = 0; i < data.length; i++) {
Then changed your var numColumns to 9 rather than 8 so that it can see the column you're trying to check with your if statement.
var numColumns = 9;

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

Sender's name in google scripts

I'm following the Google Scripts tutorials on how to send emails from a google sheet.
The code works fine and I do receive an email when I run it. However, when I check my inbox, instead of the header showing my name in the preview, it shows the full email address.
Here's the code from the tutorial:
function sendEmails() {
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, 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);
}
}
Is there any way I can set it to be my name instead of it being my full email address?
How about following modification for your script?
From :
MailApp.sendEmail(emailAddress, subject, message);
To :
MailApp.sendEmail(emailAddress, subject, message, {name: '### Your name ###'});
If this was not helpful for you, I'm sorry.

Categories