I have a Google Script running the sendEmails() function with the installable onChange trigger. This works well but I'm seeing that it also executes overnight, when no changes are made to the spreadsheet.
Anyone know what may be happening/ how to prevent this?
Here's the code that's running in the script editor:
/**
* Sends emails with data from the current spreadsheet.
*/
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 1; // Number of rows to process
// Fetch the range of cells A2:C2
var dataRange = sheet.getRange(startRow, 1, numRows, 5);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[4]; // Fifth column
var message = row[0]; // First column
var subject = row[3]; // Fourth Column
MailApp.sendEmail(emailAddress, subject, message);
}
}
In the executions/trigger log I see that a trigger executed last night at 5:07 am and the night before at 1:16am, when no changes were made to the spreadsheet
screenshot of trigger log
Wasn't able to figure out the underlying issue, but created code which prevents the script from sending an email (to Asana to create a task in this case) for any row where an email was previously sent.
var TASK_SENT= "TASK_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 UPDATE
var dataRange = sheet.getRange(startRow, 1, numRows, 48);
// 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 message = row[45] //Next Steps Column
var staff = row[1] // Your Name Column
var internal_part = row[7] //Who was the Check-in with? Column
var external_part = row[13] //What Site was your Check-in With? Column
var check_dt = row[2] //Date of Contact Column
var check_dt = Utilities.formatDate(new Date(), "GMT+1", "MM/dd/yy")
var site_disc = row[8] //What site was discussed?
var emailAddress = row[46]; // Email address column
var taskSent = row[47]; // Task_Sent column
if (taskSent != TASK_SENT) { // Prevents sending duplicates
var subject = staff + " " + 'check-in w/' + " " + internal_part + external_part + " " + 're:' + " " + site_disc + " " + check_dt + " " + 'Next Steps';
if (emailAddress == "") {
continue;}
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 48).setValue(TASK_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
Try this to see if it will eliminate the overnight emails.
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = 1;
var dataRange = sheet.getRange(startRow, 1, numRows, 5);
var data = dataRange.getValues();
for (var i=0;i<data.length;i++) {
var row = data[i];
var emailAddress = row[4]; // Fifth column
var message = row[0]; // First column
var subject = row[3]; // Fourth Column
if(emailAddress && message && subject) {
MailApp.sendEmail(emailAddress, subject, message);
}
}
}
Related
I got notification like this
Exception: Failed to send email: no recipient (line 19, file "Email")
I got no idea what happened
/**
* Sends emails with data from the current spreadsheet.
*/
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 3; // First row of data to process
var getLastRow = 900; // Number of rows to process
var dataRange = sheet.getRange(startRow, 1, getLastRow, 6);
// 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 trigger = row[0]; // kolom ke 1 TRIGGER
var emailAddress = row[2]; // Email column
var message = row[4]; // Content column
var subject = row[3]; // Subject Column
var status_email = row[5];
if ((trigger != 'FALSE') && (status_email != 'EMAIL_SENT')) { // Prevents sending duplicates
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 6).setValue('EMAIL_SENT');
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
You define getLastRow = 900 and emailAddress = row[2]
This means that from row 3 to row 900 you expect an email address to be present in each cell of column C
If you try to send an email from a row that does not contain an email address wou will get the error you metnioned
How to avoid the error?
Catch it with an if statement that checks either the cell is empty before sending the email
Sample
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 3; // First row of data to process
var getLastRow = 900; // Number of rows to process
var dataRange = sheet.getRange(startRow, 1, getLastRow, 6);
// 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 trigger = row[0]; // kolom ke 1 TRIGGER
var emailAddress = row[2]; // Email column
if(emailAddress != "" && emailAddress != " "){
var message = row[4]; // Content column
var subject = row[3]; // Subject Column
var status_email = row[5];
if ((trigger != 'FALSE') && (status_email != 'EMAIL_SENT')) { // Prevents sending duplicates
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 6).setValue('EMAIL_SENT');
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
}
I use attachment in each cell to send mail auto.
Note:
column 0: Firstname Column 4: Email Address Colum 5: Year Column 6: File Attachment.
var EMAIL_SENT = 'EMAIL_SENT';
//Sends non-duplicate emails with data from the current spreadsheet.
function autosendEmails() {
var ws = SpreadsheetApp.openById('Your Sheet Id');
var sheet= ws.getSheetByName('Mail Merge');
var startRow = 2; // First row of data to process
var numRows = ws.getLastRow(); // Number of rows to process // Fetch the range of cells E2:H3
var dataRange = sheet.getRange(startRow, 1, numRows, 7);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
// var FileID = DriveApp.getFileById('Your File Id')
for (var i = 0; i < data.length; i++) {
var row = data[i]; var emailAddress = row[4]; // First column
var Subjectmail ="Test mail"
var bodyemail = "Dear"
var pdfname = row[6];
var emailSent = row[7]; // Four column
if (emailSent !== EMAIL_SENT) {
// Prevents sending duplicates
var subject = 'Test mail';
MailApp.sendEmail(emailAddress, Subjectmail, bodyemail, {attachments: pdfname});
sheet.getRange(startRow + i, 8).setValue(EMAIL_SENT); // Make sure the cell is updated right away in case the script is interrupted SpreadsheetApp.flush();
}
}
}
Taking into consideration you're retrieving the file name from var pdfname = row[6]; , then what you must do to attach the file to your mail and send it, it's to retrieve the actual file from your drive and putting it into an array as I did in this example:
// Inside your function, just change this line
function autosendEmails() {
...
MailApp.sendEmail(emailAddress, Subjectmail, bodyemail, {
attachments: buildAttachment(pdfname) // Call this function to be able to send an attachment file
});
...
}
// Add this function to your code
function buildAttachment(pdfname){
// Initialize the array
var fileArr = [];
// Get the file form your drive
var getMyFile = DriveApp.getFilesByName(pdfname).next();
// build an array
fileArr.push(getMyFile);
// return the file within an array
return fileArr;
}
Reference
This post could help you, too.
Docs
Class MailApp
Class DriveApp
This might work better for you:
Read the comments for explanation.
function autosendEmails() {
var ws = SpreadsheetApp.openById('Your Sheet Id');
var sheet= ws.getSheetByName('Mail Merge');
var startRow = 2; // First row of data to process
var dataRange = sheet.getRange(startRow, 1, sheet.getLastRow()-1,sheet.getLastColumn());//you were missing your last column and you were grabbing an empty row and the end of your list because the third parameter is the number of rows in the data not the number of rows in the sheet.
var data=dataRange.getValues();
for (var i=0;i<data.length;i++) {
var row=data[i];
var emailAddress = row[4]; // First column
var Subjectmail ="Test mail"
var bodyemail = "Dear"
var pdfname = row[6];
var emailSent = row[7]; // Four column
if (emailSent !== "EMAIL_SENT") {
MailApp.sendEmail(emailAddress, Subjectmail, bodyemail, {attachments: ["an array of files"]});//attachments should be an array of files not an array of filenames
sheet.getRange(startRow + i, 8).setValue(EMAIL_SENT);
}
}
}
This is an example I normally use
function SendMailFC() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var message ="HELLO"
for (var i = 2; i <= 3; i++) {
var row = values[i];
var mail = row[7];
var name = row[4].substring(0,row[4].indexOf(" ",row[4].indexOf(" ")+1));
var company = row[1].substring(0,row[1].indexOf(","));
var Greeting = 'Hello ' + name+',<br><br>';
var stat = row[10];
var subject = "SUBJECT";
if(stat){
GmailApp.sendEmail(FROM, subject, "", {htmlBody: '<html>'+greeting+message+'</html>'} );
}
}
I am trying to create a Google Apps Script that works with a spreadsheet to send out an email if certain criteria is met. Specifically to send out an email if Column C equals today & column A equals false.
Link to the spreadsheet:
https://docs.google.com/spreadsheets/d/1kULWOMtZaay6PcgF5XTwVoJnKPo7JSA_AK50J8RNYzk/edit?usp=sharing
I was able to set this up to that the spreadsheet handles most of the work. Column D checks for the date, and that column A is checked and then the script will send when column D reads TRUE. I am wondering if I can have the Google Apps Script check for today's date, instead of the spreadsheet.
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 50; // Number of rows to process
var numOfColumns = sheet.getLastColumn();
// Fetch the range of cells
var dataRange = sheet.getRange(startRow, 1, numRows, numOfColumns);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
var sendTrigger = "";
var i = 0;
for (i=0;i<data.length;i++) {
var row = data[i];
var emailAddress = row[4]; // fifth column
var message = row[5]; // sixth column
sendTrigger = row[3];
if (sendTrigger == 1) {
var subject = ("This is a test of the send email function");
MailApp.sendEmail(emailAddress, subject, message);
};
};
};
I want the script to check column A and column C and send out an email if Column A equals FALSE and column C equals TODAY
Try this:
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 50; // Number of rows to process
var numOfColumns = sheet.getLastColumn();
var dataRange = sheet.getRange(startRow, 1, numRows, numOfColumns);
var data = dataRange.getValues();
var sendTrigger = "";
var dt=new Date();
var dv=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();
for (var i=0;i<data.length;i++) {
var row = data[i];
var emailAddress = row[4]; // fifth column
var message = row[5]; // sixth column
var d=new Date(row[2]);
if (!row[0] && new Date(d.getFullYear(),d.getMonth(),d.getDate()).valueOf()==dv) {
var subject = ("This is a test of the send email function");
MailApp.sendEmail(emailAddress, subject, message);
}
}
}
I'm trying to create a script that'll send me the content of a google sheet by email on a weekly basis.
Can someone point me in the right direction?
EDIT: It needs to be in the in the Body
This will send the sheet as a xls to your email. Get this to work then set a time based trigger. - also notice this is a private sheet, that gets set public for a brief moment while it emails and then sets back to private.
function getGoogleSpreadsheetAsExcel(){
try {
var ss = SpreadsheetApp.getActive();
var sheet = DriveApp.getFileById(ss.getId());
// sets sharing to public - to send out email.
sheet.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.EDIT);
var url = "https://www.googleapis.com/drive/v3/files/" + ss.getId() + "/export?mimeType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&key=" + "YOUR_KEY_GOES_HERE";
var blob = UrlFetchApp.fetch(url).getBlob();
Logger.log(url);
blob.setName(ss.getName() + ".xlsx");
var now = new Date();
MailApp.sendEmail("YOUR_EMAIL_ADDRESS_GOES_HERE", "Backup " + now , "Backup " + now , {attachments: [blob]});
} catch (f) {
Logger.log(f.toString());
}
// returns the file back to Private access
sheet.setSharing(DriveApp.Access.PRIVATE, DriveApp.Permission.EDIT);
}
Here's my solution so far but it's not clean & far from ideal:
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn());
var data = range.getValues();
var body = '';
for( var row in data ) {
for( var col in data[row] ) {
body += data[row][col] + '\t';
}
}
body += '\n';
}
Logger.log(body);
// MailApp.sendEmail('your#email.com', 'Director Dealings', body);
}
You may check this tutorial on how to send emails from a Spreadsheet.
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);
}
}
You need to use the MailApp.sendEmail(). Just be noted that there are four versions of this method
Ok I've been through this site forward and backward before asking this but for some reason I can't get the code I've implemented to work automatically. I just need the script to run (I setup a trigger already) to check the email in column 3 of sheet 5 (called Reports). I need it to send me an email with column 1 data and column 2 data if today's date matches the date given.
Can someone look at the code and give me a little help?
function sendEmails() {
var spreadsheet = SpreadsheetApp.openById('Unique ID for spreadsheet');
var sheet = spreadsheet.getSheets()[4];
var startRow = 2; // First row of data to process
var numRows = 250; // Number of rows to process
// Fetch the range of cells
var dataRange = sheet.getRange(startRow, 1, numRows, 4)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
var emailAddress = 'email#email.com';
var subject = "Report Today";
for (i in data) {
var row = data[i];
if( row[3] == true) {
var message = row[0]+row[1];
try {
MailApp.sendEmail(emailAddress, subject, message);
} catch(errorDetails) {
MailApp.sendEmail("Email#email.com", "sendEmail script error", errorDetails.message);
}
}
}
}
Make sure that the dates match to be able to compare them, by setting the time (hours, mins, secs) equal to 0.
function sendEmails() {
var spreadsheet = SpreadsheetApp.openById('[Spreadsheet_Id]');
var sheet = spreadsheet.getSheets()[4];
var startRow = 2; // First row of data to process
var numRows = 10; // Number of rows to process
// Fetch the range of cells
var dataRange = sheet.getRange(startRow, 1, numRows, 4);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
var emailAddress = 'email#email.com';
var subject = "Report Today";
var today = new Date();
today.setHours(0,0,0,0);
for (i in data) {
var row = data[i];
row[3].setHours(0,0,0,0);
if( row[3] == today ) {
Logger.log("Send email with: " + row);
var message = row[0]+row[1];
try {
MailApp.sendEmail(emailAddress, subject, message);
} catch(errorDetails) {
MailApp.sendEmail(emailAddress, "sendEmail script error", errorDetails.message);
}
}
}
}