New OAuth2 needed to run script - email

I have been using this script to send google-spreadsheet to my e-mail when modified. Can anybody help to replace the authentication section with an OAuth2 for Apps Script. OAuth 1.0 support was deprecated in 2012 and is scheduled to be shut down on April 20, 2015.
Thanks.
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [ {name: "Send Email", functionName: "sendEmail"}];
ss.addMenu("Scripts", menuEntries);
};
function sendEmail() {
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getName();
//var email = Session.getUser().getEmail();
var email = Session.getEffectiveUser();
var subject = "this is my subject";
var body = "this is my body :)";
var oauthConfig = UrlFetchApp.addOAuthService("google");
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=https://spreadsheets.google.com/feeds/");
oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
var requestData = {"method": "GET", "oAuthServiceName": "google", "oAuthUseToken": "always"};
var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key="
+ ssID + "&gid=0&portrait=true" +"&exportFormat=xls";
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {attachments:[{fileName:sheetName+".xls", content:contents, mimeType:"application//xls"}]});
};

This is an easy fix. The fetch requests requires a scope allowing drive access. You can force Apps Script to add this scope by making a call to DriveApp. Then in your fetch you add the users OAuth token to the header of the call.
function onlyToAddTheDriveScope(){
DriveApp.getRootFolder()
}
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [ {name: "Send Email", functionName: "sendEmail"}];
ss.addMenu("Scripts", menuEntries);
};
function sendEmail() {
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getName();
//var email = Session.getUser().getEmail();
var email = Session.getEffectiveUser();
var subject = "this is my subject";
var body = "this is my body :)";
var requestData = {"method": "GET",
"headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}
};
var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key="
+ ssID + "&gid=0&portrait=true" +"&exportFormat=xls";
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {attachments:[{fileName:sheetName+".xls", content:contents, mimeType:"application//xls"}]});
};

Related

Cannont read property 'namedValues' in Form Email Script

I have been trying to create an app script that will send a formatted email summary of each response to someone. I keep getting an error message returned for function onFormSubmit(e) { var responses = e.namedValues; The script is connected to the spreadsheet and not the form. I tried making the spreadsheet and then creating the form from the spreadsheet. I have deleted and reinstalled the triggers. From the other questions, I have been looking at if the e.namedValues is not working its because the script is connected to the form and not the sheet. I know that is not my problem here. This code was adapted from a project I used in the past that did work. So I am not sure what else to try. Any ideas or suggestions would be greatly appreciated.
var EMAIL_TEMPLATE_DOC_URL = 'google doc url';
var EMAIL_SUBJECT = 'Report Completed';
/**
* Installs a trigger on the Spreadsheet for when a Form response is submitted.
*/
function installTrigger() {
ScriptApp.newTrigger('onFormSubmit')
.forSpreadsheet(SpreadsheetApp.getActive())
.onFormSubmit()
.create();
}
/**
* Sends a customized email for every response on a form.
*
* #param {Object} event - Form submit event
*/
function onFormSubmit(e) {
var responses = e.namedValues;
// If the question title is a label, it can be accessed as an object field.
// If it has spaces or other characters, it can be accessed as a dictionary.
var email = 'name#gmail.com'();
var timestamp = responses.Timestamp[0];
var name = responses['Name of Staff Person completing form'][0].trim();
var researcht = responses['How much time did you spend researching?'][0].trim();
var mt = responses['How much time did you spend in meetings or doing tasks related to meetings?'][0].trim();
var wt = responses['How long did you spend practicing workshops?'][0].trim();
var rtt = responses['How long did you spend preparing for your Real Talk?'][0].trim();
var wpt = responses['How much time did you spend presenting workshops?'][0].trim();
var rtpt = responses['How much time did you spend hosting Real Talks?'][0].trim();
var misct = responses['How much time did you spend on miscellanous tasks?'][0].trim();
var topic1 = responses['First Topic Researched'][0].trim();
var topic2 = responses['Second Topic Researched'][0].trim();
var topic3 = responses['Third Topic Researched'][0].trim();
var meet1 = responses['First Meeting and Tasks'][0].trim();
var meet2 = responses['Second Meeting and Tasks'][0].trim();
var meet3 = responses['Third Meeting and Tasks'][0].trim();
var practicedw = responses['What workshop(s) did you practice?'][0].trim();
var practicedrt = responses['What Real Talk did you prepare for?'][0].trim();
var workshopname = responses['Name of Workshop Presented'][0].trim();
var workshopatt = responses['How many people attended your workshop?'][0].trim();
var workshopimp = responses['How could you improve your workshop presentation?'][0].trim();
var weval = responses['Did you email your workshop evaluations?'][0].trim();
var rtname = responses['Name of Real Talk'][0].trim();
var rtatt = responses['How many people attended your Real Talk?'][0].trim();
var rtimp = responses['How could you improve your Real Talk facilitation?'][0].trim();
var rteval = responses['Did you email your Real Talk evaluations?'][0].trim();
var misc1 = responses['Task 1'][0].trim();
var misc2 = responses['Task 2'][0].trim();
var misc3 = responses['Task 3'][0].trim();
var misc4 = responses['Task 4'][0].trim();
var concerns = responses['Third Topic Researched'][0].trim();
//get info for email
Utilities.sleep(1000);
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var lr = rows.getLastRow();
var isCellBlank = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1").getRange(1,1).isBlank();
// If there is at least one topic selected, send an email to the recipient.
var status = '';
if (!isCellBlank) {
MailApp.sendEmail({
to: email,
subject: EMAIL_SUBJECT,
htmlBody: createEmailBody(timestamp, name, researcht, mt, wt, rtt, wpt, rtpt, misct, topic1, topic2, topic3, meet1, meet2, meet3, practicedw, practicedrt, workshopname, workshopatt, workshopim, weval, rtname, rtatt, rtimp, rteval, misc1, misc2, misc3, misc4, concerns) ,
});
status = 'Sent';
}
else {
status = 'Email Not Sent';
}
// Append the status on the spreadsheet to the responses' row.
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getActiveRange().getRow();
var column = e.values.length + 1;
sheet.getRange(row, column).setValue(status);
Logger.log("status=" + status + "; responses=" + JSON.stringify(responses));
}
/**
* Creates email body and includes the links based on topic.
*
* #param {string} recipient - The recipient's email address.
* #param {string[]} topics - List of topics to include in the email body.
* #return {string} - The email body as an HTML string.
*/
function createEmailBody(timestamp, name, researcht, mt, wt, rtt, wpt, rtpt, misct, topic1, topic2, topic3, meet1, meet2, meet3, practicedw, practicedrt, workshopname, workshopatt, workshopim, weval, rtname, rtatt, rtimp, rteval, misc1, misc2, misc3, misc4, concerns) {
// Make sure to update the emailTemplateDocId at the top.
var docId = DocumentApp.openByUrl(EMAIL_TEMPLATE_DOC_URL).getId();
var emailBody = docToHtml(docId);
emailBody = emailBody.replace(/{{NAME}}/g, name);
emailBody = emailBody.replace(/{{timestamp}}/g, timestamp);
emailBody = emailBody.replace(/{{researcht}}/g, researcht);
emailBody = emailBody.replace(/{{mt}}/g, mt);
emailBody = emailBody.replace(/{{wt}}/g, wt);
emailBody = emailBody.replace(/{{rtt}}/g, rtt);
emailBody = emailBody.replace(/{{wpt}}/g, wpt);
emailBody = emailBody.replace(/{{rtpt}}/g, rtpt);
emailBody = emailBody.replace(/{{misct}}/g, misct);
emailBody = emailBody.replace(/{{topic1}}/g, topic1);
emailBody = emailBody.replace(/{{topic2}}/g, topic2);
emailBody = emailBody.replace(/{{topic3}}/g, topic3);
emailBody = emailBody.replace(/{{meet1}}/g, meet1);
emailBody = emailBody.replace(/{{meet2}}/g, meet2);
emailBody = emailBody.replace(/{{meet3}}/g, meet3);
emailBody = emailBody.replace(/{{practicedw}}/g, practicedw);
emailBody = emailBody.replace(/{{practicedrt}}/g, practicedrt);
emailBody = emailBody.replace(/{{workshopname}}/g, workshopname);
emailBody = emailBody.replace(/{{workshopatt}}/g, workshopatt);
emailBody = emailBody.replace(/{{workshopim}}/g, workshopim);
emailBody = emailBody.replace(/{{weval}}/g, weval);
emailBody = emailBody.replace(/{{ rtname}}/g, rtname);
emailBody = emailBody.replace(/{{rtatt}}/g, rtatt);
emailBody = emailBody.replace(/{{rtimp}}/g, rtimp);
emailBody = emailBody.replace(/{{rteval}}/g, rteval);
emailBody = emailBody.replace(/{{misc1}}/g, misc1);
emailBody = emailBody.replace(/{{misc2}}/g, misc2);
emailBody = emailBody.replace(/{{misc3}}/g, misc3);
emailBody = emailBody.replace(/{{misc4}}/g, misc4);
emailBody = emailBody.replace(/{{concerns}}/g, concerns);
return emailBody;
}
/**
* Downloads a Google Doc as an HTML string.
*
* #param {string} docId - The ID of a Google Doc to fetch content from.
* #return {string} The Google Doc rendered as an HTML string.
*/
function docToHtml(docId) {
// Downloads a Google Doc as an HTML string.
var url = "https://docs.google.com/feeds/download/documents/export/Export?id=" +
docId + "&exportFormat=html";
var param = {
method: "get",
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true,
};
return UrlFetchApp.fetch(url, param).getContentText();
}
I believe you are using the trigger builder wrong.
You would need to change this:
function installTrigger() {
ScriptApp.newTrigger('onFormSubmit')
.forSpreadsheet(SpreadsheetApp.getActive())
.onFormSubmit()
.create();
}
To this:
function installTrigger() {
var form = FormApp.openById('<YOUR_FORM_ID>');
ScriptApp.newTrigger('onFormSubmit')
.forForm(form)
.onFormSubmit()
.create();
}
You need to "link" the trigger to the form, not the spreadsheet.
Reference
onFormSubmit
Following Cooper's suggestion, I deleted the install trigger function. There were a few more problems with the script after that, so I made some edits. I will post the completed code, in case anyone is experiencing a similar problem.
var EMAIL_TEMPLATE_DOC_URL = 'document URL';
var EMAIL_SUBJECT = ' daily report summary for ';
var EMAIL_1 = 'name#gmail.com';
var EMAIL_2 = name#gmail.com';
//variable IDs
var timestampId = 1;
var nameId = 2;
var researchtId = 4;
var mtId = 8;
var wtId = 12;
var rttId = 14;
var wptId = 16;
var rtptId = 22;
var misctId = 29;
var topic1Id = 5;
var topic2Id = 6;
var topic3Id = 7;
var meet1Id = 9;
var meet2Id = 10;
var meet3Id = 11;
var practicedwId = 13;
var practicedrtId = 15;
var workshopnameId = 17;
var workshopattId = 18;
var workshopimpId = 19;
var wevalId = 20;
var rtnameId = 23;
var rtattId = 24;
var rtimpId = 25;
var rtevalId = 26;
var misc1Id = 30;
var misc2Id = 31;
var misc3Id = 32;
var misc4Id = 33;
var concernsId = 34;
var workstsId = 35;
function PrepEmail(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var lr = rows.getLastRow();
var responses = e.namedValues;
// If the question title is a label, it can be accessed as an object field.
// If it has spaces or other characters, it can be accessed as a dictionary.
var timestamp = sheet.getRange(lr,timestampId,1,1).getValue();
var name = sheet.getRange(lr,nameId,1,1).getValue();
var today = Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy");
var researcht = sheet.getRange(lr,researchtId,1,1).getDisplayValue();
var mt = sheet.getRange(lr,mtId,1,1).getDisplayValue();
var wt = sheet.getRange(lr,wtId,1,1).getDisplayValue();
var rtt = sheet.getRange(lr,rttId,1,1).getDisplayValue();
var wpt = sheet.getRange(lr,wptId,1,1).getDisplayValue();
var rtpt = sheet.getRange(lr,rtptId,1,1).getDisplayValue();
var misct = sheet.getRange(lr,misctId,1,1).getDisplayValue();
var topic1 = sheet.getRange(lr,topic1Id,1,1).getValue();
var topic2 = sheet.getRange(lr,topic2Id,1,1).getValue();
var topic3 = sheet.getRange(lr,topic3Id,1,1).getValue();
var meet1 = sheet.getRange(lr,meet1Id,1,1).getValue();
var meet2 = sheet.getRange(lr,meet2Id,1,1).getValue();
var meet3 = sheet.getRange(lr,meet3Id,1,1).getValue();
var practicedw = sheet.getRange(lr,practicedwId,1,1).getValue();
var practicedrt = sheet.getRange(lr,practicedrtId,1,1).getValue();
var workshopname = sheet.getRange(lr,workshopnameId,1,1).getValue();
var workshopatt = sheet.getRange(lr,workshopattId,1,1).getValue();
var workshopimp = sheet.getRange(lr,workshopimpId,1,1).getValue();
var weval = sheet.getRange(lr,wevalId,1,1).getValue();
var rtname = sheet.getRange(lr,rtnameId,1,1).getValue();
var rtatt = sheet.getRange(lr,rtattId,1,1).getValue();
var rtimp = sheet.getRange(lr,rtimpId,1,1).getValue();;
var rteval = sheet.getRange(lr,rtevalId,1,1).getValue();
var misc1 = sheet.getRange(lr,misc1Id,1,1).getValue();
var misc2 = sheet.getRange(lr,misc2Id,1,1).getValue();
var misc3 = sheet.getRange(lr,misc3Id,1,1).getValue();
var misc4 = sheet.getRange(lr,misc4Id,1,1).getValue();
var concerns = sheet.getRange(lr,concernsId,1,1).getValue();
var pname = name + '\'s';
var worksts = sheet.getRange(lr,workstsId,1,1).getDisplayValue();
// If there is at least one topic selected, send an email to the recipient.
var isCellBlank = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1").getRange(1,1).isBlank();
var status = '';
if (!isCellBlank) {
MailApp.sendEmail({
to: EMAIL_2 +','+ EMAIL_1,
subject: pname + EMAIL_SUBJECT + today,
htmlBody: createEmailBody(timestamp, name, today, worksts, researcht, mt, wt, rtt, wpt, rtpt, misct, topic1, topic2, topic3, meet1, meet2, meet3, practicedw, practicedrt, workshopname, workshopatt, workshopimp, weval, rtname, rtatt, rtimp, rteval, misc1, misc2, misc3, misc4, concerns) ,
});
status = 'Sent';
}
else {
status = 'Email Not Sent';
}
// Append the status on the spreadsheet to the responses' row.
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getActiveRange().getRow();
var column = e.values.length + 1;
sheet.getRange(row, column).setValue(status);
Logger.log("status=" + status + "; responses=" + JSON.stringify(responses));
}
/**
* Creates email body and includes the links based on topic.
*
* #param {string} recipient - The recipient's email address.
* #param {string[]} topics - List of topics to include in the email body.
* #return {string} - The email body as an HTML string.
*/
function createEmailBody(timestamp, name, today, worksts, researcht, mt, wt, rtt, wpt, rtpt, misct, topic1, topic2, topic3, meet1, meet2, meet3, practicedw, practicedrt, workshopname, workshopatt, workshopimp, weval, rtname, rtatt, rtimp, rteval, misc1, misc2, misc3, misc4, concerns) {
// Make sure to update the emailTemplateDocId at the top.
var docId = DocumentApp.openByUrl(EMAIL_TEMPLATE_DOC_URL).getId();
var emailBody = docToHtml(docId);
emailBody = emailBody.replace(/{{name}}/g, name);
emailBody = emailBody.replace(/{{today}}/g, today);
emailBody = emailBody.replace(/{{worksts}}/g, worksts);
emailBody = emailBody.replace(/{{timestamp}}/g, timestamp);
emailBody = emailBody.replace(/{{researcht}}/g, researcht);
emailBody = emailBody.replace(/{{mt}}/g, mt);
emailBody = emailBody.replace(/{{wt}}/g, wt);
emailBody = emailBody.replace(/{{rtt}}/g, rtt);
emailBody = emailBody.replace(/{{wpt}}/g, wpt);
emailBody = emailBody.replace(/{{rtpt}}/g, rtpt);
emailBody = emailBody.replace(/{{misct}}/g, misct);
emailBody = emailBody.replace(/{{topic1}}/g, topic1);
emailBody = emailBody.replace(/{{topic2}}/g, topic2);
emailBody = emailBody.replace(/{{topic3}}/g, topic3);
emailBody = emailBody.replace(/{{meet1}}/g, meet1);
emailBody = emailBody.replace(/{{meet2}}/g, meet2);
emailBody = emailBody.replace(/{{meet3}}/g, meet3);
emailBody = emailBody.replace(/{{practicedw}}/g, practicedw);
emailBody = emailBody.replace(/{{practicedrt}}/g, practicedrt);
emailBody = emailBody.replace(/{{workshopname}}/g, workshopname);
emailBody = emailBody.replace(/{{workshopatt}}/g, workshopatt);
emailBody = emailBody.replace(/{{workshopimp}}/g, workshopimp);
emailBody = emailBody.replace(/{{weval}}/g, weval);
emailBody = emailBody.replace(/{{rtname}}/g, rtname);
emailBody = emailBody.replace(/{{rtatt}}/g, rtatt);
emailBody = emailBody.replace(/{{rtimp}}/g, rtimp);
emailBody = emailBody.replace(/{{rteval}}/g, rteval);
emailBody = emailBody.replace(/{{misc1}}/g, misc1);
emailBody = emailBody.replace(/{{misc2}}/g, misc2);
emailBody = emailBody.replace(/{{misc3}}/g, misc3);
emailBody = emailBody.replace(/{{misc4}}/g, misc4);
emailBody = emailBody.replace(/{{concerns}}/g, concerns);
return emailBody;
}
/**
* Downloads a Google Doc as an HTML string.
*
* #param {string} docId - The ID of a Google Doc to fetch content from.
* #return {string} The Google Doc rendered as an HTML string.
*/
function docToHtml(docId) {
// Downloads a Google Doc as an HTML string.
var url = "https://docs.google.com/feeds/download/documents/export/Export?id=" +
docId + "&exportFormat=html";
var param = {
method: "get",
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true,
};
return UrlFetchApp.fetch(url, param).getContentText();
}

I'm trying to send an automated anniversary list. my code returns no errors but is sending no emails

function sendAnniversaryCampaing(){
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1FkKtSpvwecDEc6of2Nh37ud3qGgcNaK253S7jd7KqB0/edit#gid=0");// Sheet Url
var sheet = ss.getSheetByName("Sheet1");// Make Sure Sheet name matches at the bottom
var templateId = '157YoH_ngoESR-pwNUXfFj0dUwDYXBqOd6RCgB_cJVsQ';// the template doc with placeholders
var cDate = new Date(); //Present Day,
for(var i =2 ;i<=sheet.getLastRow(); i++){
var anDate = sheet.getRange(i,4).getValue(); // Date from SpreadSheet
if(cDate.getDate()==anDate.getDate()){
if(cDate.getMonth()==anDate.getMonth()){
var name = sheet.getRange(i,2).getValue();
var toMail= sheet.getRange(i,3).getValue();
sendMail(sheet,templateId,name,toMail);//sheet doesn't appear to be used in sendMail() Edited by Cooper.
sheet.getRange(i,5).setValue("Anniversary email sent");
}
}
}
}
function sendMail(sheet,templateId,name,toMail){
var docId = DriveApp.getFileById(templateId).makeCopy('temp').getId();
var doc = DocumentApp.openById(docId);// the temp copy
var body = doc.getBody();
body.replaceText('#name#',name);// update the temp doc
doc.saveAndClose();// save changes before conversion
var url = "https://docs.google.com/feeds/download/documents/export/Export?id="+docId+"&exportFormat=html";
var param = {
method : "get",
headers : {"Authorization": "Bearer" + ScriptApp.getOAuthToken()}
};
var htmlBody = UrlFetchApp.fetch(url,param).getContentText();
var trashed = DriveApp.getFileById(docId).setTrashed(true);// delete temp copy
MailApp.sendEmail(toMail,'Anniversary Campaing'+name,' ' ,{htmlBody : htmlBody});// send to myself to test
}
Try this:
function sendAnniversaryCampaing(){
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1FkKtSpvwecDEc6of2Nh37ud3qGgcNaK253S7jd7KqB0/edit#gid=0");// Sheet Url
var sheet = ss.getSheetByName("Sheet1");// Make Sure Sheet name matches at the bottom
var templateId = '157YoH_ngoESR-pwNUXfFj0dUwDYXBqOd6RCgB_cJVsQ';// the template doc with placeholders
var cDate = new Date().valueOf(); //Present Day,
for(var i=2;i<=sheet.getLastRow(); i++){
var anDate=new Date(sheet.getRange(i,4).getValue()).valueOf(); // Date from SpreadSheet
if(cDate==anDate){
var name=sheet.getRange(i,2).getValue();
var toMail= sheet.getRange(i,3).getValue();
sendMail(sheet,templateId,name,toMail);
sheet.getRange(i,5).setValue("Anniversary email sent");
}
}
}

How to fix error 414 uri too long when calling api for upload image to server for mobilefirst 8

i update the app from mfp 7.1 to 8. For mfp 7, the feature for uploading the image is working fine but for mfp 8 try to call same method the server throw uri too long.The server dont have any changes, only the app side
but if i sent without Photo which is base64 the api return success.The source code for camera function is exactly the same for both version mfp7.1 and 8
mfp7.1 server request(Working)
var locale = localStorageService.get('locale');
var rptList = localStorageService.get('rptList');
var channel = localStorageService.get('rptChannel');
var os = localStorageService.get('rptOs');
var type = localStorageService.get('rptOption');
var station =
localStorageService.get('mrReportHistoryDetailStation');
var desc =
localStorageService.get('mrReportHistoryDetailDesc');
var loc = localStorageService.get('rptLoc');
var accNo = localStorageService.get('rptAccNo');
var issueType = localStorageService.get('rptIssueType');
var photo = localStorageService.get('rptPhoto');
console.log(rptList);
console.log('Make Report adapter');
var deferred = $q.defer();
var invocationData = {
adapter : "Report",
procedure : "makeReport",
parameters : [{
LOCALE:locale,
CHANNEL:channel,
CLIENT_OS:os,
TYPE:type,
ISSUE_TYPE:issueType,
STATION:(type === 'GENERAL_INQUIRY')?"" : station,
CATEGORY:(type === 'GENERAL_INQUIRY')?station : "",
DESCRIPTION:desc,
LOCATION:loc,
CONTRACT_ACC_NO:accNo,
PHOTOS:photo
}]
};
console.log(JSON.stringify(invocationData));
var options = {
onSuccess : $.proxy(function (result){
deferred.resolve(result.invocationResult);
}, this),
onFailure : $.proxy(function (res){
deferred.reject(res);
}, this)
};
mfp8 (Not Working)
var locale = localStorageService.get('locale');
var rptList = localStorageService.get('rptList');
var channel = localStorageService.get('rptChannel');
var os = localStorageService.get('rptOs');
var type = localStorageService.get('rptOption');
var station =
localStorageService.get('mrReportHistoryDetailStation');
var desc = localStorageService.get('mrReportHistoryDetailDesc');
var loc = localStorageService.get('rptLoc');
var accNo = localStorageService.get('rptAccNo');
var issueType = localStorageService.get('rptIssueType');
var photo = localStorageService.get('rptPhoto');
console.log(rptList);
console.log('Make Report adapter');
var deferred = $q.defer();
var invocationData = {
LOCALE: locale,
CHANNEL: channel,
CLIENT_OS: os,
TYPE: type,
ISSUE_TYPE: issueType,
STATION: type === 'GENERAL_INQUIRY' ? '' : station,
CATEGORY: type === 'GENERAL_INQUIRY' ? station : '',
DESCRIPTION: desc,
LOCATION: loc,
CONTRACT_ACC_NO: accNo,
PHOTOS: photo
};
var resourceRequest = new WLResourceRequest(
'/adapters/Report/makeReport',
WLResourceRequest.POST
);
alert('resource');
console.log(resourceRequest);
resourceRequest.setQueryParameter('params', [invocationData]);
resourceRequest.send().then(
response => {
alert('return');
this.content = response.responseJSON;
console.log(
'Report make report====>>>' + JSON.stringify(this.content)
);
deferred.resolve(this.content);
alert('Success');
},
function(error) {
console.log('error message' + JSON.stringify(error));
deferred.reject(error);
}
);
it return success for mfp7.1 code but for mfp 8 it return error 414 uri is too long. but if without photo the api return success.
Photo is base64Image
Try using FormParams instead of QueryParams, as QueryParams will be passed in the URL and it has some limitation to number of characters. Instead you can pass your json as FormParam,
var request = WLResourceRequest(url, method, options);
request.sendFormParameters(json).then(
function(response) {
// success flow
},
function(error) {
// fail flow
}
);
For further reference, visit below link and see methods for WLResourceRequest.
http://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/api/client-side-api/javascript/client/

Email a reminder based on the status of a cell Google apps script

I am attempting to set a simple reminder email to a technician to remind when a routine service is due. I have a 2d array and code that works, but it only sends 1 email, which is the lowest row.
I'm kinda new to this, but I would like it to run through each row and send a reminder for every overdue.
Any help appreciated.
This is what I have now:
function Email_Reminder()
{;
var sheet = SpreadsheetApp.getActiveSheet();
statusArray = sheet.getDataRange().getValues();
status = "overdue";
for (i=3;i < statusArray.length;i++){
if (status == statusArray[i][6]) {
var customer = statusArray[i][0];
}
}
var email = "djens12#gmail.com"
var subject = "Reminder";
var body = "This is a reminder that the service is overdue for " +customer+ "";
MailApp.sendEmail(email,subject,body,{NoReply : true});
}
thanks
Just move your MailApp.sendEmail() inside your for loop
function Email_Reminder()
{;
var sheet = SpreadsheetApp.getActiveSheet();
statusArray = sheet.getDataRange().getValues();
status = "overdue";
var email = "djens12#gmail.com"
var subject = "Reminder";
for (i=3;i < statusArray.length;i++){
if (status == statusArray[i][6]) {
var customer = statusArray[i][0];
var body = "This is a reminder that the service is overdue for " +customer+ "";
MailApp.sendEmail(email,subject,body,{NoReply : true});
}
}
}

import private google fusion table to google docs spreadsheet

I want to build a chart to google fusion table. I know there is an option to do it with fusion table but I need to do that using google spreadsheet.
How do I import a private fusion table to a spreadsheet?
function getdata(authToken) {
query = encodeURIComponent("SELECT * FROM tableid");
var URL = "http://www.google.com/fusiontables/api/query?sql=" + query;
var response = UrlFetchApp.fetch(URL, {
method: "get",
headers: {
"Authorization": "GoogleLogin auth=" + authToken,
}
});
return response.getContentText();
}
The code above gives me the table headers only.
Don't set each cell individually as in the example below unless you need to process each bit of data. Using this is about 10x faster:
var rows = o.length;
var columns = o[0].length;
cell.offset(<startrow>, <startcolumn>, rows, columns).setValues(o);
After a deep research, finally i figured it out after a deep search and reading here.
This is how it looks for the code google docs spreadsheet app script:
function onOpen()
{
var tableID = '00000' // Add the table ID of the fusion table here
var email = UserProperties.getProperty('email');
var password = UserProperties.getProperty('password');
if (email === null || password === null) {
email = Browser.inputBox('Enter email');
password = Browser.inputBox('Enter password');
UserProperties.setProperty('email',email);
UserProperties.setProperty('password', password);
} else {
email = UserProperties.getProperty('email');
password = UserProperties.getProperty('password');
}
var authToken = getGAauthenticationToken(email,password);
query = encodeURIComponent("SELECT * FROM tableID");
var URL = "http://www.google.com/fusiontables/api/query?sql=" + query;
var response = UrlFetchApp.fetch(URL, {
method: "get",
headers: {
"Authorization": "GoogleLogin auth=" + authToken,
}
});
var tableData = response.getContentText();
var o = Utilities.parseCsv(response.getContentText());
var doc = SpreadsheetApp.getActiveSpreadsheet();
var cell = doc.getRange('a1');
var index = 0;
for (var i in o) {
var row = o[i];
var col = 0;
for (var j in row) {
cell.offset(index, col).setValue(row[j]);
col++;
}
index++;
}
}
function getGAauthenticationToken(email, password) {
password = encodeURIComponent(password);
var response = UrlFetchApp.fetch("https://www.google.com/accounts/ClientLogin", {
method: "post",
payload: "accountType=GOOGLE&Email=" + email + "&Passwd=" + password + "&service=fusiontables&Source=testing"
});
var responseStr = response.getContentText();
responseStr = responseStr.slice(responseStr.search("Auth=") + 5, responseStr.length);
responseStr = responseStr.replace(/\n/g, "");
return responseStr;
}
After that you can do whatever you want in the spreadsheet.
BTW, I still think there is a simple way to import a private table into a spreadsheet automaticly.