Send email when any value is input into first column Google Script - email

I'm looking to send an email to the recipient (clientEmail) when data is added to the first column of that specific row. The data in the first column would be a mix of numbers and letters. I've tried different methods using the following code but can never get it to send only when the value in the first column contains a value.
var EMAIL_DRAFTED = "EMAIL DRAFTED";
function draftMyEmails() {
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[1]; // Col B: Client name
var clientEmail = row[2]; // Col C: Client email
var message1 = row[3]; // Col D: First part of message
var message2 = row[4]; // Col E: Second part of message
var emailStatus = row[lastColumn - 1]; // Col F: 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>Hi ' + clientName + ',<p>';
emailBody += '<p>' + message1 + ', your requested data, ' + message2 + ', is ready.<p>';
//Send the emaiil
MailApp.sendEmail(
clientEmail, // Recipient
'Here is your data', // Subject
'', // Body (plain text)
{
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
}
}
}

Start off by changing your for loop, know the difference between ++i and i++, in this case you'd want to use the latter. See: difference between ++i and i++.
for (var i = 0; i < data.length; i++) {
All you need to do after that is add a check in your if statement for the column in question. Note: you could define this separately like you've done for the other variables. I'll provide 2 examples and you can pick which you'd prefer to use, both will function the same.
//option 1
if (emailStatus !== EMAIL_DRAFTED && clientEmail && row[0]) {
//option 2
var checkData = row[0];
if (emailStatus !== EMAIL_DRAFTED && clientEmail && checkData) {
In the end your code should look something like this:
var EMAIL_DRAFTED = "EMAIL DRAFTED";
function draftMyEmails() {
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[1]; // Col B: Client name
var clientEmail = row[2]; // Col C: Client email
var message1 = row[3]; // Col D: First part of message
var message2 = row[4]; // Col E: Second part of message
var emailStatus = row[lastColumn - 1]; // Col F: Email Status
// Prevent from drafing duplicates and from drafting emails without a recipient
if (emailStatus !== EMAIL_DRAFTED && clientEmail && row[0]) {
// Build the email message
var emailBody = '<p>Hi ' + clientName + ',<p>';
emailBody += '<p>' + message1 + ', your requested data, ' + message2 + ', is ready.<p>';
//Send the emaiil
MailApp.sendEmail(
clientEmail, // Recipient
'Here is your data', // Subject
'', // Body (plain text)
{
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
}
}
}

Related

BCC doesn't seem to function as an option of sendEmail - name and replyTo work though

function myFunction() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Welcome");
var targetSheet = ss.getSheetByName("Done");
var startRow = 2;
var lr = sheet.getLastRow();
var dataRange = sheet.getRange(startRow, 1, lr-1, 6);
var data = dataRange.getValues();
var colNumber = sheet.getLastColumn()-1;
var delRows = [];
for (var i = 0; i < data.length; i++) {
var row = data[i];
var id = row[0];
var emailAddress = row[1];
var date = row[2];
var city = row[3];
var bccmail = row[6];
var Sender = 'XXXXXX';
var reply = 'xxxxxx#xxxxxxx.com';
if (emailAddress.match('#') === null){
continue;
};
var subject = row[4];
var message = "Hey " + id + ", welcome in the team " + row[5];
MailApp.sendEmail(emailAddress, subject, message, {bcc: bccmail,name: Sender,replyTo: reply});
var targetRange = targetSheet.getRange(targetSheet.getLastRow()+1, 1, 1, colNumber);
var sourceRange = sheet.getRange(i+startRow, 1, 1, colNumber);
sourceRange.copyTo(targetRange);
delRows.push(i+startRow);
}
delRows.reverse().forEach(ri=>{sheet.deleteRow(ri)});
Almost all the script works fine. When it comes to sendEmail, I have tried to follow these guidelines and use sendEmail(recipient, subject, body, options). 2 out of 3 options work fine but BCC doesn't work at the moment. Do you know what I am doing wrong? Can BCC be a variable?
The problem is in this line:
var bccmail = row[6];
dataRange is defined as a range with only 6 columns. data is a 2D array with the values of dataRange. row is a 1D array with a single row of data. JavaScript array indexes only start at 0, so the values are in row[0] to row[5].
Please check your sheet in which column does the bcc string is defined and count the index from 0.
Reference:
Arrays in JavaScript

Send multiple attachments using DriveApp.getFileById in Google Apps Script

I am trying to get a script running that takes multiple file IDs from a Google Sheet and attaches them to an email. I cannot get multiple files to be attached using DriveApp.getFileById.
The script runs and fires off an email, but with no attachments.
function createAndSendDocument(values) {
// Get the email address of the active user
var email = Session.getActiveUser().getEmail();
// Get the name of the document to use as an email subject line.
var subject = 'New Paperwork';
//Let's add the attachments variables
var attachmentstring = values["Which documents do you want to attach?"];
var array = attachmentstring.toString().split(",");
var blobs = [];
var x = 0;
for (var i = 0; i < array.length; i++) {
//check if even
if (i % 2 === 0) {
blobs[x] = array[i];
x++;
}
}
// Append a new string to the "url" variable to use as an email body.
var body = 'your doc: ' + blobs[0] + blobs[1] + array[0] + array[1] + "length:" + array.length;
// Send yourself an email with a link to the document.
GmailApp.sendEmail(email, subject, body, {attachments: blobs});
}
I edited the original post to include the snippet of code. Here is the output of the blobs and array.
undefinedundefinedW-4 2019.pdf1YjQqFNze8VX0L6wZ9O3Y9AJNznR8jfxqlength:4
This code worked:
function createAndSendDocument(values) {
// Get the email address of the active user
var email = Session.getActiveUser().getEmail();
// email subject line.
var subject = 'New Paperwork';
// add the attachments variables
var attachmentstring = values["Which documents do you want to attach?"];
var array = attachmentstring.toString().split(",");
var blobs = [];
var x = 0;
for (var i = 0; i < array.length; i++) {
//check if even
if (i % 2 === 0) {
}
else
{
blobs[x] = DriveApp.getFileById(array[i]).getBlob();
x++;
}
}
// an email body.
var body = 'Hello';
// Send an email with attachments
GmailApp.sendEmail(email, subject, body, {attachments: blobs});
}

Sending multiple attachments using Google Spreadsheet and Google Script

Im trying to send multiple attachments using Google Spreadsheet but I get the following error "Cannot retrieve the next object: iterator has reached the end."
It does work, because it sends the e-mail to the first email-address in the list, but it fails for the second one.
I have seen similar questions here about it, but no solutions resolve my issue.
Here is the script:
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 1;
var numRows = 2;
var dataRange = sheet.getRange(startRow, 1, numRows, 2);
var file1 = DriveApp.getFilesByName('Maandbrief December.pdf');
var file2 = DriveApp.getFilesByName('Weekendbrief 7-9 december.pdf');
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[0];
var message = row[1];
var subject = "Maandbrief December en weekendbrief 7-9 december";
MailApp.sendEmail({to:emailAddress, subject:subject, body:message, attachments: [file1.next(), file2.next()]})
}}
Thank you for your help.
Try this:
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 1;
var numRows = 2;
var dataRange = sheet.getRange(startRow, 1, numRows, 2);
var files1 = DriveApp.getFilesByName('Maandbrief December.pdf');
while(files1.hasNext()){var file1=files1.next();}
var files2 = DriveApp.getFilesByName('Weekendbrief 7-9 december.pdf');
while(files2.hasNext()){var file2=files2.next();}
var data = dataRange.getValues();
for (var i=0;i<data.length;i++) {
var row = data[i];
var emailAddress = row[0];
var message = row[1];
var subject = "Maandbrief December en weekendbrief 7-9 december";
MailApp.sendEmail({to:emailAddress, subject:subject, body:message, attachments: [file1, file2]})
}
}
or this:
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 1;
var numRows = 2;
var dataRange = sheet.getRange(startRow, 1, numRows, 2);
var n1=0;
var n2=0;
var files1 = DriveApp.getFilesByName('Maandbrief December.pdf');
while(files1.hasNext()){var file1=files1.next();n1++;}
var files2 = DriveApp.getFilesByName('Weekendbrief 7-9 december.pdf');
while(files2.hasNext()){var file2=files2.next();n2++}
var data = dataRange.getValues();
if(n1==1 && n2==1){
for (var i=0;i<data.length;i++) {
var row = data[i];
var emailAddress = row[0];
var message = row[1];
var subject = "Maandbrief December en weekendbrief 7-9 december";
MailApp.sendEmail({to:emailAddress, subject:subject, body:message, attachments: [file1, file2]});
}
}else{
throw('More than one file with given name.');
}
}

Reference Cell for Email Address

First code is what I am currently using, I am trying to get my email address to reference in a cell. I've found another script that does this but when I try to combine them, it doesn't work.
function getGoogleSpreadsheetAsExcel(){
try {
var ss = SpreadsheetApp.getActive();
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key="
+ ss.getId() + "&exportFormat=xlsx";
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
blob.setName(ss.getName() + ".xlsx");
MailApp.sendEmail("Email Address Here", "Subject Here", "Body of Email
Here", {attachments: [blob]});
} catch (f) {
Logger.log(f.toString());
}
}
And trying to combine this to it to reference cells for me instead of edited the script.
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(sheet.getSheetByName('Email Test'))
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);
}
}
Again both work on there own, but wont work when combined.
This is what I have compiled and it does send the email and attachement, but just to myself, no other recipients. Needing at least it to go to 6 other people at once.
function getGoogleSpreadsheetAsExcel(){
try {
var ss = SpreadsheetApp.getActive();
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key="
+ ss.getId() + "&exportFormat=xlsx";
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
blob.setName(ss.getName() + ".xlsx");
var sheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(sheet.getSheetByName('Email Test'))
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, {attachments: [blob]});
}
}
catch (f) {
Logger.log(f.toString());
}
}

Deleting a row based on date - Date values

My query relates to this Google Form responses spreadsheet. I'm trying to adapt the script I got from here.
function cleanup() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Form responses 1');
var values = sheet.getDataRange().getValues();
var InAYear = (Date.now()/86400000 + 25569) + 365;
for (var i = values.length - 1; i >= 0; i--) {
if ( values[i][5] >= InAYear) {
sheet.deleteRow(i+1);
}
}
}
I'm trying to get this to compare the date in the Start Date column of the sheet with the date in a year from now and delete the row if the column entry is greater than this (ie. if the date on the sheet is more than a year in advance). However, I obviously don't understand how to get the two different dates in the same format because examining variable values when debugging shows wildly different values.
Try the following script code:
function cleanup() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Form responses 1');
var values = sheet.getDataRange().getValues();
var today = Utilities.formatDate(new Date(), ss.getSpreadsheetTimeZone(), 'MM/dd/yyyy')
for (var i = values.length - 1; i >= 0; i--) {
if ( values[i][4] != '' && dateDiffInDays(values[i][4],today) > 365 ) {
sheet.deleteRow(i+1);
}
}
};
function dateDiffInDays(d1,d2) {
var date1 = new Date(d1);
var date2 = new Date(d2);
var timeDiff = date1.getTime() - date2.getTime();
return Math.ceil(timeDiff / (1000 * 3600 * 24));
};
It looks like I have it working, and sending me an email.
function cleanup(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Form responses 1');
var values = sheet.getDataRange().getValues();
var today = new Date();
var InAYear = new Date();
InAYear.setFullYear( today.getFullYear()+1 );
var emailaddress = "****";
var subject = "Annual Leave Request";
var message = "Annual Leave has been requested as follows:" + "\n\n";
for (var i = values.length - 1; i >= 0; i--) {
if ( values[i][4] > InAYear ) {
sheet.deleteRow(i+1);
subject = "Annual Leave Request - Rejected";
message = "The following annual leave request was rejected due to being more than one year in advance:" + "\n\n";
}
}
for(var field in e.namedValues) {
message += field + ':'
+ "\n" + e.namedValues[field].toString() + "\n\n";
}
MailApp.sendEmail(emailaddress, subject, message);
}
Thank you to Kishan, without who's help I would not have been able to get to this stage.