Google App Script problem in Loop emails when conversation length are long - javascript

Reference to the previous question to Filter Gmail body and paste in Spreadsheet
I had created below a google app script and set a trigger for after every 5 minutes:
function GetEmailsData(){
// SKIP TO OUT OF OFFICE HOURS AND DAYS
var nowH=new Date().getHours();
var nowD=new Date().getDay();
if (nowH>19||nowH<8||nowD==0) { return }
// START OPERATION
var Gmail = GmailApp;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var MasterSheet = ss.getSheetByName("Master");
var index = 2;
var aa = 0; // count already update entries
var na = 0; // count not update entries
var lasttime = MasterSheet.getRange("Z1").getValue(); // in spreadsheet i record the last time of email scanned, so next trigger will search after that
Logger.log(lasttime);
var cdate = new Date();
var ctime = cdate.getTime();
var qDate = MasterSheet.getRange("Z1").getValue();
Logger.log("QDATE IS " + qDate);
//problem # 1: from filter is not working.
// SEARCH EMAIL
var query = 'from: email id, subject: email subject, after:' + Math.floor((qDate.getTime()) /1000);
var threadsNew = Gmail.search(query);
Logger.log(threadsNew.length);
//loop all emails
for(var n in threadsNew){
var thdNew = threadsNew[n];
var msgsNew = thdNew.getMessages(); 
var msgNew = msgsNew[msgsNew.length-1];
// GET ATTACHMENT
//var bodyNew = msgNew.getBody();
var plainbody = msgNew.getPlainBody();
var subject = msgNew.getSubject();
var Etime = msgNew.getDate();
//var attachments = msgNew.getAttachments();
//var attachment = attachments[0];
Logger.log(Etime);
Logger.log(subject);
//Logger.log(plainbody);
var tdata = plainbody.trim();
var data = parseEmail001(tdata);
//Logger.log(data);
// First Check Email Date
var newdate = new Date();
var dd = newdate.getDate();
var mm = newdate.getMonth() + 1;
var yyyy = newdate.getFullYear();
var cd = dd + "-" + mm + "-" + yyyy
//Logger.log(new Date());
//Logger.log(cd);
if (Etime.getDate() != dd) {return}
// first check current sheet exist or not
// DATE DECLARATION IS ABOVE
var itt = ss.getSheetByName(cd);
if (!itt) {
ss.insertSheet(cd);
var itt = ss.getSheetByName(cd);
var ms = ss.getSheetByName("Master");
var hlc = ms.getLastColumn();
var headings = ms.getRange(1,1,1,hlc).getValues();
itt.getRange(1,1,1,hlc).setValues(headings);
}
var MasterSheet = ss.getSheetByName(cd);
var mlr = MasterSheet.getLastRow();
var mlc = MasterSheet.getLastColumn();
//check data already updated or not
var NewDepositSlipNumber = Number(data[2]).toFixed(0);
//Logger.log(Number(data[2]).toFixed(0));
var olddata = MasterSheet.getDataRange().getValues();
//Logger.log(olddata[1][2]);
for(var i = 0; i<olddata.length;i++){
if(olddata[i][2] == NewDepositSlipNumber){
//Logger.log(i + 1);
var status = 'Already Update'
Logger.log(status);
break;
}
else{
var status = 'Not Update'
//Logger.log(status);
}
}
// count how many updated and how many not.
if(status == 'Not Update'){
na = na + 1;
}
else{
aa = aa + 1;
}
if(status == 'Not Update'){
MasterSheet.appendRow(data);
Logger.log("Data Updated");
}
}
//problem # 2: if conversation length are long, it is not reaching there
var lastscantime = threadsNew[0].getLastMessageDate();
var master = ss.getSheetByName("Master");
master.getRange("Z1").setValue(lastscantime);
Logger.log(lastscantime);
master.getRange("Z2").setValue(new Date());
Logger.log(new Date());
Logger.log("Total " + threadsNew.length + " found, out of which " + aa + " are already updated, while " + na + " are updated.");
}
function parseEmail001(message) {
var replaces = [
'Branch Code',
'Branch Name',
'Slip No',
'BL Number',
'Type Of Payment',
'Customer Name',
'Payer Bank',
'Payer Bank Branch',
'Transaction Type',
'Amount',
'Posting Date',
'Value Date'
];
return message.split('\n').slice(0, replaces.length)
.map((c,i) => c.replace(replaces[i], '').trim());
}
This script is working fine but I have two problems:
I placed three filters in query 1) from 2) subject 3) after
but sometimes it gives me emails that are from the same ID but different subject.
as per my observation, and I verified it by using debug mode if the conversation length is long I guess more than 30 it will not reach the end part of the script. it skipping my last step as I also marked it in the above script. and if conversation length is less it works smoothly.
explanation: in other words, from morning to evening it's working fine after every five minutes, but the next day it gets the problem, then I manually update my spreadsheet master sheet Z1 value as of today's date and time, then it works fine till tonight.

You might be reaching a script limitation. Possibly the custom function runtime.But it can be any, you should see an error if it didn't finish.

Related

Send email based on cell value

I am trying to have this script loop per column. If a date in the column is the same as today's date, the script will send an email using the persons name and email address detailed in the same row.
Table of Expiry Dates
function myFunction()
{
var spreadSheet = SpreadsheetApp.getActiveSheet();
var dataRange = spreadSheet.getDataRange();
var data = dataRange.getValues();
var date = Utilities.formatDate(new Date(), "GMT", "dd/MM/yyyy")
var engcheck1 = dataRange.getColumn[2];
for (var i = 1; i < data.length; i++)
if (engcheck1 == date)
{
var row = data[i];
var emailAddress = row[7]; //position of email header — 1
var name = row[1]; // position of name header — 1
var subject = "Your Currency for Engineering is now expired";
var text = "Please note that your currency has expired today (" + date +"). You are now unauthorised to carry out any engineering tasks until you have been signed off by a member of the engineering team.";
var message = "Dear " + name + "," + "\n\n" + text + "\n\n" + "Please get back in currency at your earliest convenience." + "\n\n" + "Many thanks," + "\n" + "Dominic Paul"
MailApp.sendEmail(emailAddress, subject, message);
}(i);
}
Without the 'If' statement, the script will loop through each row and sending out an email address. When I include the 'If' statement, nothing is sent to the email addresses. Either I am using the if statement incorrectly or I am not targeting the column accurately. I tried creating a variable engcheck1 for column 2 ONLY but no email is sent despite today being one of the dates in column 2 (C).
I did not understand, what is var engcheck1 = dataRange.getColumn[2];.
If you need to send and email if date is the same as the value in C column, provided column C has type Plain text, this is the answer:
function myFunction() {
var spreadSheet = SpreadsheetApp.getActiveSheet();
var dataRange = spreadSheet.getDataRange();
var lastRow = SpreadsheetApp.getActiveSpreadsheet().getDataRange().getNumRows();
var dateData = spreadSheet.getRange("C1:C" + lastRow).getDisplayValues().flat();
var data = dataRange.getValues();
var date = Utilities.formatDate(new Date(), "GMT", "dd/MM/yyyy")
for (var i = 1; i < data.length; i++) {
var rowDate = dateData[i];
var row = data[i];
// if the date in row is the same as date variable
if (rowDate === date) {
var emailAddress = row[7]; //position of email header — 1
var name = row[1]; // position of name header — 1
var subject = "Your Currency for Engineering is now expired";
var text = "Please ...";
var message = "Dear ...";
MailApp.sendEmail(emailAddress, subject, message);
};
}
}
Try this:
function myFunction() {
const ss = SpreadsheetApp.getActive();
var sh = ss.getActiveSheet();
var rg = sh.getDataRange();
var vs = rg.getValues();
const dt = new Date();
var dtv = new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();
vs.forEach((r,i) => {
let d = new Date(r[2]);
let dv = new Date(d.getFullYear(),d.getMonth(),d.getDate()).valueOf();
if(dv == dtv ) {
//send you email
}
})
}

How to do Gmail merge with file attachment in one script. I have done my mail merge script but i don't know how to add file attachment

This my mini project.Click here.
Gmail merge with 5 file attachments
Have to send email through google sheets with attachment
Must have email sent time
The requirements is in the image
this coding for mail merge in google sheets.I don't know where to add the file attachment and i don't know how to add.
function sendEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").activate();
var lr = ss.getLastRow();
var templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();
var quotaLeft = MailApp.getRemainingDailyQuota();
//Logger.log(quotaLeft);
if ((lr - 1) > quotaLeft) {
Browser.msgBox("You have " + quotaLeft + " left and you are trying to send " + (lr - 1) + " emals.Emails were not send.")
} else {
for (var i = 2; i <= lr; i++) {
var currentEmail = ss.getRange(i, 1).getValue();
var currentClass = ss.getRange(i, 3).getValues();
var currentName = ss.getRange(i, 2).getValues();
var messageBody = templateText.replace("{name}", currentName).replace("{class}", currentClass);
var subjectLine = "Reminder:" + currentClass + " Upcoming Class";
MailApp.sendEmail(currentEmail, subjectLine, messageBody);
}// class for loop
}// class for function
}
Answer
To add an attachment you have to add a fourth parameter called options to the function MailApp.sendEmail. It is an object that can different advanced parameters. To define the attachment you can use the following example:
Code
var options = {
attachments: [file1, file2]
}
MailApp.sendEmail(currentEmail, subjectLine, messageBody, options);
However, I recommend you to use GmailApp.sendEmail. It is more integrated with Gmail and has more functionalities.
update
The image you attach is a bit confusing looking at your code, however, I have edited it so you can see how to perform the task you want in a more optimal way.
Please check the value assignment carefully. As you can see, I only use once the method getRange and getValues to get all the values of a particular row:
function sendEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").activate();
var lr = ss.getLastRow();
var templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();
var quotaLeft = MailApp.getRemainingDailyQuota();
//Logger.log(quotaLeft);
if ((lr - 1) > quotaLeft) {
Browser.msgBox("You have " + quotaLeft + " left and you are trying to send " + (lr - 1) + " emals.Emails were not send.")
} else {
for (var i = 2; i <= lr; i++) {
var rowValues = ss.getRange(i, 1, 1, 13).getValues()
var name = rowValues[0]
var organizationName = rowValues[1]
var eventName = rowValues[2]
var email = rowValues[3]
//
var file1 = DriveApp.getFilesByName(rowValues[7]).next()
var file1 = DriveApp.getFilesByName(rowValues[8]).next()
var options = {
attachments: [file1, file2]
}
var messageBody = templateText.replace("{name}", currentName).replace("{class}", currentClass);
var subjectLine = "Reminder:" + currentClass + " Upcoming Class";
MailApp.sendEmail(currentEmail, subjectLine, messageBody, options);
}// class for loop
}// class for function
}
With all this information you should have no problem achieving your goal. If you run into any errors, let me know, but keep in mind that the code is not ready to use.
Reference
MailApp.sendEmail
GmailApp.sendEmail
Sheet: getRange
Sheet: getValues

Exception: Argument cannot be null: prompt Error in google Scripts

I have created a mail merge with a confirmation pop up in order to confirm the script has not been run recently, and also to double check the user intends to send emails. The script works perfectly, but annoyingly I receive the following error when run:
Stating; Exception: Argument cannot be null: prompt
I would like to get rid of this if possible. I attach my code.
//Creates a functional log of how many emails are sent and to how many branches
function confirmationWindow(){
var numberSent = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Validations').getRange('D3').getValue();
var numberOfVios = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Validations').getRange('D2').getValue();
var ui = SpreadsheetApp.getUi();
var ui = SpreadsheetApp.getUi();
ui.alert(
'You have succesfully sent ' + numberOfVios + ' violations, to ' + numberSent + ' branches.',)
}
function saveData() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Log');
var date = new Date()
var user = Session.getActiveUser().getEmail();
var range = ss.getRange("A:B")
var numberSent = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Validations').getRange('D2').getValue();
var branchNumber = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Validations').getRange('D3').getValue();
ss.appendRow([date,user,numberSent,branchNumber]);
}
var EMAIL_SENT = 'True';
function sendEmails() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Output');
var sheetI= SpreadsheetApp.getActive().getSheetByName('Input');
var sheetC = SpreadsheetApp.getActive().getSheetByName('Control');
var emailNum = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Validations').getRange('D3').getValue();
var startRow = 2;
var numRows = emailNum;
var dataRange = sheet.getRange(startRow, 1, numRows, 6);
sheetI.setTabColor("ff0000");
saveData()
var data = dataRange.getValues();
for (var i in data) {
var row = data[i];
var emailAddress = row[3];
var message = row[5] + "\n\nT\n\nT\n\nT";
var message = message.replace(/\n/g, '<br>');
var subject = row[4];
MailApp.sendEmail(emailAddress, subject, message,{htmlBody:message});
sheet.getRange(startRow + i - 18, 8).setValue(EMAIL_SENT);
sheetC.getRange(startRow + i - 18, 3).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}
confirmationWindow()
}
function recentSend() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Log');
var lastR = sheet.getLastRow();
var recentRun = sheet.getRange('A' + lastR).getValue();
if(lastR=1){var recentlySent = 'False'}
var today = new Date().valueOf()
var recentDate = recentRun
var sec = 1000;
var min = 60 * sec;
var hour = 60 * min;
var day = 24 * hour;
var difference = today - recentDate
var hourDifference =Math.floor(difference%day/hour);
if (hourDifference > '12'){var recentlySent = 'False'}
else {var recentlySent = 'True'}
return(recentlySent)
}
function recentlySentTrue(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Log');
var lastR = sheet.getLastRow();
var recentUser = sheet.getRange('B' + lastR).getValue();
var recentQuant = sheet.getRange('C' + lastR).getValue();
var recentT = sheet.getRange('A' + lastR).getValue();
var recentSendLog = recentT.toString();
var recentTime = recentSendLog.slice(16,21)
var recentDate = recentSendLog.slice(0,11)
var ui = SpreadsheetApp.getUi();
var result = ui.alert(
'Are you sure you wish to send?',
'The user, ' + recentUser + ' ,recently sent ' + recentQuant + ' emails, at ' + recentTime + ' on ' + recentDate,
ui.ButtonSet.YES_NO);
if (result == ui.Button.YES) {
ui.alert(recentlySentFalse());
}
else {
}
}
function recentlySentFalse(){
var ui = SpreadsheetApp.getUi();
var ui = SpreadsheetApp.getUi();
var result = ui.alert(
'Are you Sure you wish to send?',
'Are you sure you want to send these violations?',
ui.ButtonSet.YES_NO);
if (result == ui.Button.YES) {
ui.alert(sendEmails());
} else {
}
}
function confirm(){
var recentlySent = recentSend();
if (recentlySent == 'True'){
recentlySentTrue()
}
else{recentlySentFalse()
}
}
Any help would be great.
Explanation:
Your ui.alert() calls that have function arguments such as recentlySentFalse() are not valid, since the functions do not have return statements, hence they return the default value of null. ui.alert() calls need at least a prompt message.
Solution 1:
Put the function call after the UI alert message:
if (result == ui.Button.YES) {
ui.alert('Sending message...');
recentlySentFalse();
}
Solution 2:
If you do not want excessive alerts, just remove ui.alert and call the function immediately.
if (result == ui.Button.YES) {
recentlySentFalse();
}
References:
Class UI | Apps Script

Adding event to calendar via Google Apps script - error when calculating end time more than one hour after start

I have a simple app in which users complete some basic details of a meeting in a google sheet and then export these to their google calendar. Script as follows:
function exportEvents() {
var sheet = SpreadsheetApp.getActiveSheet();
var headerRows = 1;
var range = sheet.getDataRange();
var data = range.getValues();
// var calId = sheet.getRange("H2:H2").getValue();
var calId = "xxxxxxxxxxxx";
var cal = CalendarApp.getCalendarById(calId);
for (i=0; i<data.length; i++) {
if (i < headerRows) continue;
var row = data[i];
var date = new Date(row[1]);
var title = row[2];
var initial = row[0];
var concatTitle = initial + " - " + title;
var tstart = new Date(row[3]);
tstart.setDate(date.getDate());
tstart.setMonth(date.getMonth());
tstart.setYear(date.getYear());
// var tstop = new Date(row[4]);
var tstop = new Date(tstart + row[4]);
tstop.setDate(date.getDate());
tstop.setMonth(date.getMonth());
tstop.setYear(date.getYear());
var loc = row[5];
var desc = row[6];
var id = row[7];
try {
var event = cal.getEventSeriesById(id);
}
catch (e) {
// do nothing - we just want to avoid the exception when event doesn't exist
}
if (!event) {
var newEvent = cal.createEvent(concatTitle, tstart, tstop, {description:desc,location:loc}).getId();
row[7] = newEvent;
}
else {
event.setTitle(concatTitle);
event.setDescription(desc);
event.setLocation(loc);
var recurrence = CalendarApp.newRecurrence().addDailyRule().times(1);
event.setRecurrence(recurrence, tstart, tstop);
}
debugger;
}
range.setValues(data);
}
The whole thing works great, except for when the user puts more than 60 mins as the length of the meeting in column 4. Anything up to 59 mins works great and the event is logged with the correct start and end time. However, when I enter 60 or more mins, the error reads 'Event start time must be before event end time."
I'm sure I'm doing something very simple very wrong, but any help would be greatly appreciated.

Run Google script on single sheet instead of entire spreadsheet

With my spreadsheet, I have 2 Google forms tied to 2 sheets. When a form gets submitted the script executes and does it's thing. However, I only want the script to execute based on a submission from a single sheet. As it is now, the script executes when either of the forms get submitted.
My two sheets are:
Job Submission
and Order Submission
Any advice?
// Work Order
// Get template from Google Docs and name it
var docTemplate = ""; // *** replace with your template ID ***
var docName = "Work Order";
var printerId = "";
function addDates() {
var date = new Date(); // your form date
var holiday = ["09/04/2017","10/09/2017","11/23/2017","12/24/2017","12/25/2017","01/01/2018"]; //Define holiday dates in MM/dd/yyyy
var days = 5; //No of days you want to add
date.setDate(date.getDate());
var counter = 0;
if(days > 0 ){
while (counter < days) {
date.setDate(date.getDate() + 1 );
var check = date.getDay();
var holidayCheck = holiday.indexOf(Utilities.formatDate(date, "EDT", "MM/dd/yyyy"));
if (check != 0 && check != 6 && holidayCheck == -1) {
counter++;
}
}
}
Logger.log(date) //for this example will give 08/16/2017
return date;
}
function createNewDoc(values) {
//Get information from form and set as variables
var email_address = "";
var job_name = values[1];
var order_count = values[2];
var order_form = values[7];
var print_services = values[3];
var priority = values[5];
var notes = values[6];
var formattedDate = Utilities.formatDate(new Date(), "EDT", "MM/dd/yyyy");
var expirationDate = Utilities.formatDate(addDates(), "EDT", "MM/dd/yyyy");
// Get document template, copy it as a new temp doc, and save the Doc's id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName+' for '+job_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document's body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyJobName', job_name);
copyBody.replaceText('keyOrderCount', order_count);
copyBody.replaceText('keyOrderForm', order_form);
copyBody.replaceText('keyPrintServices', print_services);
copyBody.replaceText('keyPriority', priority);
copyBody.replaceText('keyNotes', notes);
copyBody.replaceText('keyDate', formattedDate);
copyBody.replaceText('keyDue', expirationDate);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "New Job Submission - " + job_name;
var body = "Here is the work order for " + job_name + ". Job is due " + expirationDate + ".";
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});
// Move file to folder
var file = DriveApp.getFileById(copyId);
DriveApp.getFolderById("").addFile(file);
file.getParents().next().removeFile(file);
var newDocName = docName + ' for ' + job_name;
return [copyId, newDocName];
}
function printGoogleDocument(copyId, docName) {
// For notes on ticket options see https://developers.google.com/cloud-print/docs/cdd?hl=en
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR"
},
duplex: {
type: "NO_DUPLEX"
},
}
};
var payload = {
"printerid" : "",
"content" : copyId,
"title" : docName,
"contentType" : "google.kix", // allows you to print google docs
"ticket" : JSON.stringify(ticket),
};
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
method: "POST",
payload: payload,
headers: {
Authorization: 'Bearer ' + GoogleCloudPrint.getCloudPrintService().getAccessToken()
},
"muteHttpExceptions": true
});
// If successful, should show a job here: https://www.google.com/cloudprint/#jobs
response = JSON.parse(response);
if (response.success) {
Logger.log("%s", response.message);
} else {
Logger.log("Error Code: %s %s", response.errorCode, response.message);
}
return response;
}
// When Form Gets submitted
function onFormSubmit(e) {
var values = e.values;
var returnedDocValues = createNewDoc(values);
var copyId = returnedDocValues[0];
var docName= returnedDocValues[1];
printGoogleDocument(copyId, docName);
}
Edit:
I'm not sure how to do a complete or verifiable example since it's dependent on the form submission. I don't often work with javascript so I'm still learning.
Anyway, I updated my onFormSubmit function, however, my other functions have failed to execute. The script doesn't create the doc and in turn doesn't get sent to the google cloud print
// When Form Gets submitted
function onFormSubmit(e) {
// Initialize
var rng = e.range;
var sheet = rng.getSheet();
var name = sheet.getName();
// If the response was not submitted to the right sheet, exit.
if(name != "Job Submission") return;
var values = e.values;
var returnedDocValues = createNewDoc(values);
var copyId = returnedDocValues[0];
var docName= returnedDocValues[1];
printGoogleDocument(copyId, docName);
}
If your onFormSubmit function is on a script bounded to the spreadsheet, the event object includes a range object. You could use getSheet to get the sheet and then getName to get the sheet name.
Example:
function onFormSubmit(e){
// Initialize
var rng = e.range;
var sheet = rng.getSheet();
var name = sheet.getName();
// If the response was not submitted to the right sheet, exit.
if(name != "Responses 1") return;
//Otherwise continue
}
Going off of Ruben's suggestion, here is what I ended up with
function onFormSubmit(e) {
// Initialize
var name = e.range.getSheet().getName();
// If the response was not submitted to the right sheet, exit.
if (name != "Job Submission") return;
var values = e.values;
var returnedDocValues = createNewDoc(values);
var copyId = returnedDocValues[0];
var docName = returnedDocValues[1];
printGoogleDocument(copyId, docName);
}

Categories