been using MailApp script to automatically send emails from within a google sheet for several years. developed my script from an example i found online and reverse engineered it until i could make it work (i am not a coder!). worked brilliantly for months/years...
but recently it is no longer functioning. i get a daily email summary of errors which states that EMAIL_SENT is not defined, but when running the script in debug mode it times out after the logger.log(user) - so does appear to hang on the EMAIL_SENT variable.
As i say, this has been running brilliantly for many months, but appears to have stopped around july 22nd.
i have included the script below in case it is something simple:
function autoemailES() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("ESautoemail");
//var lastRow = sheet.getLastRow();
var startRow = 2; // First row of data to process
var numRows = sheet.getLastRow() -1; // Number of rows to process
var EMAIL_SENT = 'EMAIL_SENT';
// Fetch the range of cells A2:G
var dataRange = sheet.getRange(startRow, 1, numRows, 30);
// 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 emailSent = row[7]; // 8th column
if (emailSent !== EMAIL_SENT) { // Prevents sending duplicates
var superMail = row[2]; // 3rd column
var responseNo = row[3]; // 4th column
var user = row[0]; // 1st column
var firstName = row[1]; // 2nd column
var pdfLink = row[5]; // 6th column
var pdfID = row[6]; // 7th column
Logger.log(responseNo) //these logger lines just display the values for each of the variables in debugging
Logger.log(superMail)
Logger.log(user)
Logger.log(pdfLink)
Logger.log(pdfID)
var file = DriveApp.getFileById(pdfID);
var subject = 'IBTPHEM MSF results for ' + user;
var message = 'Dear Educational Supervisor,' + "\n" +
'This is an automated notification that your trainee, ' + firstName + ', has now received a quorate number of MSF responses.'+"\n"+
'The anonymised summary of responses is attached in PDF format, or can be downloaded from the link below.'+"\n" + pdfLink +"\n"+
'Further submissions will be added automatically (the trainee is notified for each), but the pdf will need downloading again'+"\n"+
'Please feel free to share this with your trainee however you see fit - we are now releasing the results via the ES in case there is any feedback that may require debriefing or handling more delicately.'+"\n"+
'Please do let me know of any problems or concerns?'+"\n"+
'Kind Regards,' + "\n" +
'IBTPHEM MSF'
MailApp.sendEmail(superMail,subject, message,{
name: 'IBTPHEM MSF',
replyTo: 'dr_nick#doctors.org.uk',
attachments: [file.getAs(MimeType.PDF)]});
sheet.getRange(startRow + i, 8).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}
}
}
I would be really grateful for any help to identify my problem.
thanks!
dr_nick
(i cannot easily share the sheet in its entirity as it contains a fair bit of senstive/confidential information - though I suppose I could make an anonymised version if this is necessary/helpful?)
This is the same script with a try catch block. It will only log things if you have an error.
function autoemailES() {
const ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("ESautoemail");
var startRow = 2;
var EMAIL_SENT = 'EMAIL_SENT';
var dataRange = sheet.getRange(startRow, 1, sheet.getLastRow() - startRow + 1, 30);
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
try{
var row = data[i];
var emailSent = row[7];
if (emailSent !== EMAIL_SENT) {
var superMail = row[2];
var responseNo = row[3];
var user = row[0];
var firstName = row[1];
var pdfLink = row[5];
var pdfID = row[6];
var file = DriveApp.getFileById(pdfID);
var subject = 'IBTPHEM MSF results for ' + user;
var message = 'Dear Educational Supervisor,' + "\n" +
'This is an automated notification that your trainee, ' + firstName + ', has now received a quorate number of MSF responses.' + "\n" +
'The anonymised summary of responses is attached in PDF format, or can be downloaded from the link below.' + "\n" + pdfLink + "\n" +
'Further submissions will be added automatically (the trainee is notified for each), but the pdf will need downloading again' + "\n" +
'Please feel free to share this with your trainee however you see fit - we are now releasing the results via the ES in case there is any feedback that may require debriefing or handling more delicately.' + "\n" +
'Please do let me know of any problems or concerns?' + "\n" +
'Kind Regards,' + "\n" +
'IBTPHEM MSF'
MailApp.sendEmail(superMail, subject, message, {
name: 'IBTPHEM MSF',
replyTo: 'dr_nick#doctors.org.uk',
attachments: [file.getAs(MimeType.PDF)]
});
sheet.getRange(startRow + i, 8).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}
}
catch(e){
Logger.log('responseNo: %s\nsuperMail: %s\nuser: %s\npdfLink:%s\npdfID: %s',responseNo,superMail,user,pdfLink,pdfID);
Logger.log(e);
}
}
}
Try setting up another spreadsheet and adjust the data so that it doesn't send data to your clients and see if it will generate any errors. Also if you could share a copy of the new spreadsheet as a markdown table that would enable us to test it a little. But be careful about sharing private information
Related
Currently have this script to send out approval request emails to relevant approvers. However would want for this to be sent out as a thread instead of spamming individual emails. Is there anything I could insert into my script to help with this? Thanks in advance!
function sendEmail(){
//drawing from the active sheet.
var sheet = SpreadsheetApp.getActiveSheet();
//setting variables & getting the data from the sheet you are on
var startRow = 2; // First row of data to process
var numRows = sheet.getLastRow(); // Number of rows to process
var numColumns = sheet.getLastColumn(); //Number of columns to process
var dataRange = sheet.getRange(startRow, 1, numRows-(startRow-1), numColumns);
var data = dataRange.getValues();
var complete = "sent";
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var aemail = row[16]; //approver’s email
var approval = row[13]; //approval column
var reqrow = row[17]; //req row number
var emailed = row[18]; //already emailed
//check to see if an email has NOT been sent
if (emailed != complete){
//check to see if not yet approved
if(approval == ""){
//When done, it will mark it as sent in the last column
var sent = sheet.getRange(startRow + i, numColumns);
//Setting it to send the email to the approver's email
var email = aemail;
//Change the text as desired
var subject = "Quotation Request";
// \n is a line break
var emailtext = "Hi, " +
"\n\nYou have quotation request pending your review and approval on row " + reqrow + ".\n" +
"\nPlease go to the link below for your further action.\n" +
"\nhttps://docs.google.com/spreadsheets/d/x123/edit?usp=sharing \n" +
"\nThis is an automated email. Thanks."
//Send the email
GmailApp.sendEmail(email, subject, emailtext);
//Assign “sent” to to the last cell in the row so the email does not send again
sent.setValue(complete);
}
}
}
}
You would need to add parameter Message-Id in every email to achieve threading in recipient's mailbox.
However, GmailApp.sendEmail does not support this feature.
https://developers.google.com/apps-script/reference/gmail/gmail-app#sendEmail(String,String,String)
I am attempting to write a script to email employees account details after they have been hired. The script finally sends an email. and does not send duplicates. However it is not reading the information as expected across each row. I have no idea what is going on. I am also truly lost over the line
sheet.getRange(startRow + i-18,1).setValue(EMAIL_SENT);
at the bottom and why I had to put in the -18 in order to get the EMAIL_SENT written to the correct row in the sheet.
Here is the script:
var EMAIL_SENT = 'EMAIL_SENT';
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 55; // Number of rows to process
var dataRange = sheet.getRange(startRow, 1, numRows, 9);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
var subject = "MCS Account Info";
for (i in data) {
// clear variables between loops
var email1 = "";
var ccs = "";
var message = "";
var row = data[i];
var email1 = row[4];
if(row[4] !== "") var ccs = row[4];
if(row[5] !== "") var ccs = ccs + ", " + row[5];
if(row[6] !== "") var ccs = ccs + ", " + row[6];
if(row[7] !== "") var ccs = ccs + ", " + row[7];
var message = row[8];
// just so I can see what is in each variable will be removed when working
Logger.log("email - ",row[3],"subject - ",subject,"message - ",message,"bcc - ",ccs);
if (row[0] !== EMAIL_SENT) {
if(row[2] !== "") {
MailApp.sendEmail(row[3], subject, message, {
bcc: ccs
});
sheet.getRange(startRow + i-18,1).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}
}
}
}
and a link to the test sheet I am using: https://docs.google.com/spreadsheets/d/1CzrMlsgwvkzp_w4IjZcOkSl7rU9T8qnBYBYi2luwWkg/edit?usp=sharing
In case the link does not work this is a sheet with 9 columns.
A - EMAIL_SENT message
B - # to look up info from another sheet
C - Username
D - User's Email address
E - H Additional Email Addresses for BCC
G - Message to send
Sheet will have several hundred entries as the year progresses right now I am looking at the first 56 rows even though my sheet only has 2 entries in it.
Try this:
function sendEmails() {
var sheet=SpreadsheetApp.getActiveSheet();
var startRow=2;
var numRows=55;
var dataRange=sheet.getRange(startRow,1,numRows,9);
var data=dataRange.getValues();
var subject="MCS Account Info";
for (var i=0;i<data.length;i++) {
var ccs="";
var row=data[i];
var email1=row[4];
if(row[4]!="") var ccs=row[4];
if(row[5]!="") var ccs=ccs + ", " + row[5];
if(row[6]!="") var ccs=ccs + ", " + row[6];
if(row[7]!="") var ccs=ccs + ", " + row[7];
var message=row[8];
if (row[0]!='EMAIL_SENT' && row[2]!="") {
MailApp.sendEmail(row[3], subject, message, {bcc: ccs});
sheet.getRange(i+startRow,1).setValue('EMAIL_SENT');
}
}
}
I am building a badge sending program using Google sheets and everything is going great so far. There is a control page that once marked yes and the script runs, sends an email to the email listed and inserts information from that page, including the recipients name. I want to be able to find the name of the person I'm sending a badge email to, use that name to activate a sheet, and then date stamp a certain cell on that sheet. I'm having trouble finding the name value.
The email and date stamp is working on the control page, but I'm having trouble figuring out the logic to determine the name value to open each person's individual page. The Logger just shows all the names in the range and I only want the names to show that are receiving emails/badges.
function sendEmails3() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Badge Issuing Central")
var startRow = 2; // First row of data to process
// Fetch the range of cells
var dataRange = sheet.getRange(startRow, 1, sheet.getLastRow()-1, 7);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
data.forEach(function(row,i) {
var name = row[0]; // First column
var badge = row[1]; // Second column
var recomendations = row[2]//third column
var awarded = row [3] // fourth column
var email = row [4] // fifth column
var dateEmailed = row [5] // 6th column
var emailSent = row[6]; // Seventh column
if (emailSent != EMAIL_SENT && awarded == 'Yes') { // Prevents sending duplicates
var body = 'Hi ' + name + '<br><br>' +
'Congratulations! You have recieved a badge!<br><br>' +
'Your teammates think you are doing great lately.<br><br>' +
'You were nominated at least twice by those around you, and you are being awarded:<br><br>' +
"<em>" + badge + '<br><br>' +
"Make sure you check out your Badge Pathway to see how you're doing!<br><br>" +
'Thanks, <br>' +
"Jordan, Mark, and Jarrod";
var subject = 'Congratulations! You have earned a badge!';
GmailApp.sendEmail(email, subject, "", { htmlBody: body } );
sheet.getRange(startRow + i, 7).setValue(EMAIL_SENT);
sheet.getRange(startRow + i, 6).setValue(d);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
if (emailSent != EMAIL_SENT && awarded == 'Yes') {
var nameTab = sheet.getRange(2,1,sheet.getLastRow()-1,1).getValues();
Logger.log(nameTab);}
});}
Try this:
function sendEmails3() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName("Badge Issuing Central")
var data=sh.getRange(2, 1, sh.getLastRow()-1, 7).getValues();
for(var i=0;i<data.length;i++) {
var name=data[i][0]; // First column
var badge=data[i][1]; // Second column
var recomendations=data[i][2]//third column
var awarded=data[i][3] // fourth column
var email=data[i][4] // fifth column
var dateEmailed=data[i][5] // 6th column
var emailSent = data[i][6]; // Seventh column
if(emailSent != "EMAIL_SENT" && awarded=='Yes') {
var body=Utilities.formatString('Hi %s <br><br>Congratulations! You have recieved a badge!<br><br>Your teammates think you are doing great lately.<br><br>You were nominated at least twice by those around you, and you are being awarded:<br><br><em> %s<br><br>Make sure you check out your Badge Pathway to see how you\'re doing!<br><br>Thanks, <br>Jordan, Mark, and Jarrod', name,badge);
var subject = 'Congratulations! You have earned a badge!';
GmailApp.sendEmail(email, subject, "", { htmlBody: body } );
sh.getRange(i + 2, 7).setValue("EMAIL_SENT");
sh.getRange(i + 2, 6).setValue(Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "MMddyyyy HH:mm:ss"));
}
}
}
I am new to coding scripts in google and come into a problem I can not work through and my script "mentor" is still not that experienced and can't figure it out either.
I am trying to update a different tab on my sheet from a pivot table when I use my script to send out bulked emails.
So the link below will bring you to the dummy sheet built off my real sheet. The 'PM' tab column L is what I am trying to update. It starts at 1 on all jobs. The emails are sent out by the Blue button on the next tab 'Follow up email' (this is just a pivot table so I can always adjust who is getting the emails easily). But I cant figure out how to have it update the 'PM' tab with the button at the same time as the emails go out.
Link to the open shared spreadsheet. Feel free to play around if you can help.
https://docs.google.com/spreadsheets/d/1_hipIj4suI2xMGUrZhMTBDvkQv9Y9O3JRNNQUpSeAP0/edit?usp=sharing
(only got the emails to send properly so far)
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var rows = sheet.getLastRow()
var dataRange = sheet.getRange(2, 1, rows-1, 7);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[1]; // Second column
var message = 'Hello, we have submitted this job ' + row[2] + ' days Ago. ' + row[4] + ' \n\n' + ' -' + row[5];
var subject = row[0]; // First column
MailApp.sendEmail(emailAddress, subject, message);
}
}
I need the button to send out emails on the 'Follow up email' tab and at the same time "email counter" (column L) would get 1 added to it on the 'PM' Tab. This way I can keep track of how many times that job was emailed from the sheet.
Try this code:
function sendEmails() {
var pmSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PM");
var emailSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Follow up email");
var startRow = 2; // First row of data to process
var rows = emailSheet.getLastRow()
var dataRange = emailSheet.getRange(2, 1, rows-1, 7);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[1]; // Second column
var message = 'Hello, we have submitted this job ' + row[2] + ' days Ago. ' + row[4] + ' \n\n' + ' -' + row[5];
var subject = row[0]; // First column
MailApp.sendEmail(emailAddress, subject, message);
updatePM(pmSheet, emailAddress);
}
}
function updatePM(sheet, email){
var value;
var emails = sheet.getRange("G3:G" + sheet.getLastRow()).getValues();
for (var i = 0; i < emails.length; i++)
if (emails[i][0] == email){
value = sheet.getRange("K" + (i+3)).getValue() + 1
sheet.getRange("K" + (i+3)).setValue(value);
}
}
I changed the way you got the sheets just to be safe, then I just wrote a small function that gets called after the email is sent, which checks the list of emails in the PM sheet and then updates the value in the sent email column.
I am still learning the ropes here. Based on code suggested by other contributors, I put together a script to send reminder emails to consultants who record their time entries using a Google Form. The spreadsheet first imports calendar entries with all the Job information for each consultant. After the calendar entries are imported, if the consultant has not yet recorded their time entry, the following script will send them an email with a reminder to do so:
function sendReminder() {
var rmndrFrom = "XYZ, Inc.";
var myemail = "support#xyz.com";
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Pending");
var numRows = sheet.getLastRow();
var lastCol = sheet.getLastColumn();
var dataRange = sheet.getRange(2, 1, numRows, lastCol); // row 1 is the header row
var sheetData = dataRange.getValues();
for (var i = 0; i < sheetData.length; ++i) {
var row = sheetData[i];
if (row[0]){
var jobNumb = row[0]; // Job Number
var conName = row[2]; // Consultant Name
var conMail = row[3]; // Consultant Email
var jobDate = row[4]; // Date
// format email string
var subject = "Time Entry Reminder: " + conName + " / Job " + jobNumb;
try {
var conMsgH = 'This is a reminder for you to record your time entry for Job #<strong>' + jobNum + '/' + jobDate + '</strong>';
// strip HTML for plain text message
var conMsgP = conMsgH.replace(/\<br\/\>/gi, '\n').replace(/(<([^>]+)>)/ig, "");
// send reminder to consultants
MailApp.sendEmail(conMail, subject, conMsgP, { htmlBody:conMsgH, name:rmndrFrom });
} catch (e) { // error handler
MailApp.sendEmail(myemail, "Error in sending reminder email.", e.message);
}
}
}
}
So basically, this script parses the Pending sheet, if column A has a Job Number, it will send a reminder email to the consultant with that Job Number. However, a single consultant may have several job numbers to their name. I would like the script to send a single email to each consultant with a list of the Job Numbers for which they have to record their time entries.
Thanks in advance for your kind help. Any suggestions on how to optimize the code will also be very much appreciated.
There are a number of ways that you can approach this. One way is to keep a sheet with the consultants emails, names and a list of their job numbers. Load this data into your script, a list of all job ids and the job info. Then filter the job ids based on the consultants list and build your email, or you could just send that list of numbers for a very short script.
Another way is to do all of that sorting per consultant in the code and send out the emails that way. This is the approach I've taken, and I've also made use of the iterative JS functions map, filter and reduce more details at MDN.
The code is posted below, but if you would like to take a look at it attached to a spreadsheet and commented (as well as the functions to build that extra sheet with just the consultants info on it) take a look here.
Below is my iteration of your function. I hope it is helpful for your situation:
var rmndrFrom = "XYZ, Inc.";
var myemail = "me#emailisawesome.com";
var subject = "Time Entry Reminder";
function sendReminder() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Pending");
var numRows = sheet.getLastRow();
var lastCol = sheet.getLastColumn();
var sheetData = sheet.getRange(2, 1, numRows-1, lastCol).getValues();
var cons = sheet.getRange(2,3,numRows-1,1).getValues().reduce(flatten_).filter(getUniqueConsultants_);
cons.forEach(sendEmail_, sheetData);
}
function sendEmail_(consultant) {
var consultantsJobs = this.filter(getJobsForConsultant_, consultant);
var jobList = consultantsJobs.map(buildJobLine_).join("<br>");
try {
var conMsgH = "Hi " + consultant + ",<br>";
conMsgH += "This is a reminder for you to record your time entry for the following jobs:<br><br>";
conMsgH += jobList;
conMsgH += "<br><br>Thank you for your cooperation.";
var conMsgP = conMsgH.replace(/\<br\/\>/gi, '\n').replace(/(<([^>]+)>)/ig, "");
MailApp.sendEmail(consultantsJobs[0][3], subject, conMsgP, {htmlBody:conMsgH, name:rmndrFrom});
} catch (e) {
MailApp.sendEmail(myemail, "Error in sending reminder email.", e.message);
}
}
function buildJobLine_(job) {
return "Job #" + job[0] + " on " + Utilities.formatDate(job[4], Session.getTimeZone(), "MMM dd yyyy");
}
function getJobsForConsultant_(row) {
return row[2] == this;
}
function getUniqueConsultants_(v,i,a) {
return a.indexOf(v) == i;
}
function flatten_(a,b) {
return a.concat(b);
}
I must say that fooby's answer is far beyond my JS skills, I'm sure it will work nicely but I still feel like proposing something different (and simpler from my pov), just for the fun of it ;-)
The main difference with your original script is the sorting of the array that allowed me to detect duplicate names and threat it accordingly. The html composition could be far better for sure but that was not your main request.
Here is the code
function sendReminder() {
var rmndrFrom = "XYZ, Inc.";
var myemail = "support#xyz.com";
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Pending");
var initial = "Hi conName,<BR>This is a reminder for you to record your time entry for the following jobs : <BR><BR><table border = 1 cellpadding = 3 bgcolor='#FFFFBB'><TR><TD>";
var sheetData = sheet.getDataRange().getValues();// simplified code to get the data array
sheetData.shift();//skips the headers
sheetData.sort(function(x,y){
var xp = x[2];// sort on column 3 but you can change here...
var yp = y[2];// sort on column 3 but you can change here...
return xp == yp ? 0 : xp < yp ? -1 : 1;// sort ascending, eventually change here...
});
// Logger.log(sheetData);// sorted
var last = sheetData.length
var i = 1;//index 0 is handled outside the loop
var row = sheetData[0];
var subject = "Time Entry Reminder: " + row[2] + " / Job "
var conMsgH = initial
var msgComponent = makeline_(row)
subject += msgComponent[0]
conMsgH += msgComponent[1]
while (i<last){
if(sheetData[i][2]!=sheetData[i-1][2]||i==last-1){
sendData_(sheetData[i-1][3],sheetData[i-1][2],subject,conMsgH)
var subject = "Time Entry Reminder: " + sheetData[i][2] + " / Job "
var conMsgH = initial;
}
msgComponent = makeline_(sheetData[i])
subject += msgComponent[0]
conMsgH += msgComponent[1]
++i
}
}
function sendData_(conMail,conName,subject,conMsgH){
conMsgH = conMsgH.substr(0,conMsgH.length-8)+'</TABLE>'
conMsgH = conMsgH.replace('conName',conName)
var conMsgP = conMsgH.replace(/<\/tr>/ig, '\n').replace(/<br>/ig, '\n').replace(/(<([^>]+)>)/ig, "")
subject = subject.substr(0,subject.length-2);// remove the last '+ '
// Logger.log(subject)
// Logger.log(conMsgH)
Logger.log(conMsgP)
// Logger.log(conMail)
try{
// send reminder to consultants
MailApp.sendEmail(conMail, subject, conMsgP, { htmlBody:conMsgH, name:rmndrFrom });
} catch (e) { // error handler
// MailApp.sendEmail(myemail, "Error in sending reminder email.", e.message);
}
}
function makeline_(row){
var jobNumb = row[0]; // Job Number
var conName = row[2]; // Consultant Name
var conMail = row[3]; // Consultant Email
var descr = row[1]; // description
var FUS1=new Date(row[4]).toString().substr(25,6)+':00';// get timezone of this event, taking care of daylight savings
var jobDate = Utilities.formatDate(row[4], FUS1, "MMM dd yyyy # hh:mm aaa"); // Date
var subject = jobNumb+' + ';
var conMsgH = 'Job #'+jobNumb + '</TD><TD>' + jobDate + '</TD><TD>' + descr + '</TD></TR><TR><TD>';
return [subject,conMsgH];
}
EDIT : made some improvement in the mail format, used a table to show jobs & dates + removed some bugs ;-) (to be honest, I made this also for my personal use as I am having almost the same use case )