I have a script that performs a CRM system on my company and I am using Fusion table as a database. Every time i enter a new record, this record is saved on this fusion table. When the save action is performed, I use the follow code to make a copy of the data, that is passed to the database, in on spreadsheet so I have a backup of the data:
function AtualizarSpreadsheet(e)
{
var app = UiApp.getActiveApplication();
var planilha = SpreadsheetApp.openById(SPREADSHEET_ID);
var sheet = planilha.getActiveSheet();
var enviado = "NÃO";
var id = e.parameter.id;
var nomeDoReclamante = e.parameter.nomeDoReclamante;
var telefone = e.parameter.telefone;
var ddd = e.parameter.ddd;
var prefixo = e.parameter.prefixo;
var sufixo = e.parameter.sufixo;
var email = e.parameter.email;
var regiao = e.parameter.regio;
var categoria = e.parameter.categoria;
var produto = e.parameter.produto;
var subcategoria = e.parameter.subcategoria;
var versaoDeSoftware = e.parameter.versoDeSoftware;
var dataDeInicio = e.parameter.dataDeInicio;
var dia = e.parameter.dia;
var mes = e.parameter.ms;
var ano = e.parameter.ano;
var tituloDoProblema = e.parameter.ttuloDoProblema;
var descricao = e.parameter.descrio;
var status = e.parameter.status;
var prioridade = e.parameter.prioridade;
var informarEngenharia = e.parameter.informarEngenharia;
var dataDeRegistro = e.parameter.dataDeRegistro;
var horaDeRegistro = e.parameter.horaDeRegistro;
var historico = e.parameter.histrico;
var ordem = e.parameter.ordem;
sheet.s
sheet.appendRow([enviado,
id,
nomeDoReclamante,
telefone,
ddd,
prefixo,
sufixo,
email,
regiao,
categoria,
produto,
subcategoria,
versaoDeSoftware,
dataDeInicio,
dia,
mes,
ano,
tituloDoProblema,
descricao,
status,
prioridade,
informarEngenharia,
dataDeRegistro,
horaDeRegistro,
historico,
ordem]);
return app;
}
On the spreadsheet I perform a function onOpen() to send one email everytime the spreadsheet is oppened.
However when my fusion table script performs the command: SpreadsheetApp.openById(SPREADSHEET_ID); the onOpen() function is not being triggered. Even if I oppen the spreadsheet I cant have that function runned.
The onOpen() function is detailed bellow:
function onOpen()
{
MailApp.sendEmail("EMAIL", "SUBJECT", "BODY");
}
What am I doing wrong?
You are attempting to call a service (MailApp) that is not supported in a simple trigger. You would need to call your onOpen() function something different, and attach an installable "on open" trigger to it instead.
https://developers.google.com/apps-script/understanding_triggers
Related
I'm developing a word addin that pulls xml data from our servers and binds it to a rich text content control. The user should only be able to format the data within the content control but can't edit or delete the data.
This is the code i've been able to come up with but it's not working..
var ooxmlPackage = new DOMParser().parseFromString(
'<pkg:package xmlns:pkg="http://schemas.microsoft.com/office/2006/xmlPackage"></pkg:package>',
"text/xml"
);
var ooxmlPart = ooxmlPackage.createElement("pkg:part");
ooxmlPart.setAttribute("pkg:name", "/_rels/.rels");
ooxmlPart.setAttribute("pkg:contentType", "application/vnd.openxmlformats-package.relationships+xml");
ooxmlPart.setAttribute("pkg:padding", "512");
var ooxmlxmlData = ooxmlPackage.createElement("pkg:xmlData");
var ooxmlRelationships = ooxmlPackage.createElement("Relationships");
ooxmlRelationships.setAttribute("xmlns", "http://schemas.openxmlformats.org/package/2006/relationships");
var ooxmlRelationship = ooxmlPackage.createElement("Relationship");
ooxmlRelationship.setAttribute("Id", "rId1"); //TODO: generate unique ID
ooxmlRelationship.setAttribute(
"Type",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"
);
ooxmlRelationship.setAttribute("Target", "word/document.xml");
ooxmlRelationships.appendChild(ooxmlRelationship);
ooxmlxmlData.appendChild(ooxmlRelationships);
ooxmlPart.appendChild(ooxmlxmlData);
var ooxmlDocPart = ooxmlPackage.createElement("pkg:part");
ooxmlDocPart.setAttribute("pkg:name", "/word/document.xml");
ooxmlDocPart.setAttribute(
"pkg:contentType",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"
);
var ooxmlDocPartxmlData = ooxmlPackage.createElement("pkg:xmlData");
var ooxmlDocument = ooxmlPackage.createElement("w:document");
ooxmlDocument.setAttribute("xmlns:w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
ooxmlDocument.setAttribute("xmlns:w15", "http://schemas.microsoft.com/office/word/2012/wordml");
var ooxmlDocumentBody = ooxmlPackage.createElement("w:body");
var ooxmlDocumentParagraph1 = ooxmlPackage.createElement("w:p");
var ooxmlContentControl = ooxmlPackage.createElement("w:sdt");
var sdtPr = ooxmlPackage.createElement("w:sdtPr");
//var lk = ooxmlPackage.createElement("w:lock");
//lk.setAttribute("w:val", "sdtContentLocked");
//sdtPr.appendChild(lk);
var alias = ooxmlPackage.createElement("w:alias");
alias.setAttribute("w:val", "MyControl");
sdtPr.appendChild(alias);
var id1 = ooxmlPackage.createElement("w:id");
id1.setAttribute("w:val", "1382295294");
sdtPr.appendChild(id1);
//var appr = ooxmlPackage.createElement("w15:appearance");
//appr.setAttribute("w15:val", "hidden");
//sdtPr.appendChild(appr);
sdtPr.appendChild(ooxmlPackage.createElement("w:showingPlcHdr"));
//var plchdlr = ooxmlPackage.createElement("w:placeholder");
//var docPrt = ooxmlPackage.createElement("docPart");
//docPrt.setAttribute("w:val", "defaultPlaceHolder_-1854013440");
//plchdlr.appendChild(docPrt);
//sdtPr.appendChild(plchdlr);
var bindingNode = ooxmlPackage.createElement("w15:dataBinding");
//bindingNode.setAttribute("w:prefixMappings","xmlns:ns0='custom'");
bindingNode.setAttribute("w:xpath","/Root[1]/Node[1]");
bindingNode.setAttribute("w:storeItemID", "{C2F77B86-6131-4922-803B-54FACB654C16}");
sdtPr.appendChild(bindingNode);
ooxmlContentControl.appendChild(sdtPr);
var sdtContent = ooxmlPackage.createElement("w:sdtContent");
var parag = ooxmlPackage.createElement("w:p");
var r = ooxmlPackage.createElement("w:r")
var t = ooxmlPackage.createElement("w:t")
//t.innerHTML= '[This is a test]';
r.appendChild(t);
parag.appendChild(r);
sdtContent.appendChild(parag);
ooxmlContentControl.appendChild(sdtContent);
ooxmlDocumentBody.appendChild(ooxmlDocumentParagraph1);
ooxmlDocumentBody.appendChild(ooxmlContentControl);
ooxmlDocument.appendChild(ooxmlDocumentBody);
ooxmlDocPartxmlData.appendChild(ooxmlDocument);
ooxmlDocPart.appendChild(ooxmlDocPartxmlData);
ooxmlPackage.documentElement.appendChild(ooxmlPart);
ooxmlPackage.documentElement.appendChild(ooxmlDocPart);
var serializer = new XMLSerializer();
var ooxmlPackageString = serializer.serializeToString(ooxmlPackage);
console.log(ooxmlPackageString);
Office.context.document.setSelectedDataAsync(ooxmlPackageString, { coercionType: "ooxml" });
Office.context.document.customXmlParts.getByIdAsync(
'<Root xmlns=""> <Node>VALUE1</Node></root>',
function (result) { });
It just inserts an empty content control when it runs, it doesn't map the xml node data as expected.
This is the extended version of my previous question.
I want to send email once in a week to the recipients based on the status column.
Sheet Link: https://docs.google.com/spreadsheets/d/1GC59976VwB2qC-LEO2sH3o2xJaMeXfXLKdfOjRAQoiI/edit#gid=1546237372
The previous code is attached in the sheet.
From the sheet, When the Status column will be new and ongoing, a table will be generated with column Title, Link and due date and send a single email to the recipients even they are repeated.
In the sheet, For resource Anushka, Status New appeared twice and Ongoing once. The table will be like-
Anushka || New || 10/25/2022
Anushka || New || 10/25/2022
Anushka || Ongoing || 10/25/2022
And after creating it, it will send single email to each recipients though they have appeared several times.
I have done it for getting multiple emails whatever the status is with the help of another commenter from stackflow but I want to modify it and change it. The code for this one is a bit longer as I have two helper gs file, html table code and the main one. That's why I am not writing all the codes here. But in the sheet from the extension, one can see my code.
If anyone give me suggestions how to change or modify the logic, it will be appreciated.
Code
function macro(){
// get range of cell with data from A1 to any cell near having value (call data region)
var table = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet3").getRange("A1").getDataRegion();
var header=table.getValues()
var resource=header[0][1]
var status_r=header[0][3]
var due_date_r=header[0][5]
var link_r=header[0][10]
// create custom table filtered by the column having header "State" where the value match "New"
var filterTable = new TableWithHeaderHelper(table)
.getTableWhereColumn("Status").matchValueRegex(/(New)/);
// for each row matching the criteria
for(var i=0; i< filterTable.length() ; i++){
// Get cell range value at column Mail
var mail = filterTable.getWithinColumn("Email").cellAtRow(i).getValue();
// Any other value of column Target Value
var resource_col = filterTable.getWithinColumn("Resource").cellAtRow(i).getValue();
var status_col = filterTable.getWithinColumn("Status").cellAtRow(i).getValue();
var due_date_col = filterTable.getWithinColumn("Due Date").cellAtRow(i).getValue();
var link_col = filterTable.getWithinColumn("Link").cellAtRow(i).getValue();
var new_data=[[resource_col,status_col,due_date_col,link_col]]
var htmltemplate=HtmlService.createTemplateFromFile("email")
htmltemplate.resource=resource
htmltemplate.status_r=status_r
htmltemplate.due_date_r=due_date_r
htmltemplate.link_r=link_r
htmltemplate.new_data=new_data
var htmlformail=htmltemplate.evaluate().getContent()
var subjectMail = "Automation Support Services Actions Items";
var dt1 = new Date()
var dt2 = due_date_col
// get milliseconds
var t1 = dt1.getTime()
var t2 = dt2.getTime()
var diffInDays = Math.floor((t1-t2)/(24*3600*1000));
// 24*3600*1000 is milliseconds in a day
console.log(diffInDays);
// Send email
MailApp.sendEmail({
to:mail ,
subject: subjectMail,
htmlBody:htmlformail,
});
}
}```
2 loops can make the job.
// get range of cell with data from A1 to any cell near having value (call data region)
var table = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet3").getRange("A1").getDataRegion();
// init html header data
var header=table.getValues()
var resource=header[0][1]
var status_r=header[0][3]
var due_date_r=header[0][5]
var link_r=header[0][10]
var listOfEmails = [];
var tableWithHeader = new TableWithHeaderHelper(table)
// get all email
for(var i=0; i< tableWithHeader.length() ; i++){
var mail = tableWithHeader.getWithinColumn("Email").cellAtRow(i).getValue();
listOfEmails.push(mail)
}
// filter all email to get unique liste of email
var uniqueMailList = listOfEmails.filter((c, index) => {
return listOfEmails.indexOf(c) === index;
});
for(var i=0; i< uniqueMailList.length; i++){
// get mail of target i
var mail = uniqueMailList[i]
// filter table using mail of target i and status
var mailTable = new TableWithHeaderHelper(table)
.getTableWhereColumn("Status").matchValueRegex(/(New)/)
.getTableWhereColumn("Email").matchValue(mail);
// initialise html template
var htmltemplate=HtmlService.createTemplateFromFile("email")
htmltemplate.resource=resource
htmltemplate.status_r=status_r
htmltemplate.due_date_r=due_date_r
htmltemplate.link_r=link_r
var new_data = []
var htmlformail
// loop into the filtered table of target i only
for(var j=0; j< mailTable.length() ; j++){
// Any other value of column Target Value
var resource_col = mailTable.getWithinColumn("Resource").cellAtRow(j).getValue();
var status_col = mailTable.getWithinColumn("Status").cellAtRow(j).getValue();
var due_date_col = mailTable.getWithinColumn("Due Date").cellAtRow(j).getValue();
var link_col = mailTable.getWithinColumn("Link").cellAtRow(j).getValue();
new_data.push([resource_col,status_col,due_date_col,link_col])
}
htmltemplate.new_data=new_data
htmlformail=htmltemplate.evaluate().getContent()
var subjectMail = "Automation Support Services Actions Items";
var dt1 = new Date()
var dt2 = due_date_col
// get milliseconds
var t1 = dt1.getTime()
var t2 = dt2.getTime()
var diffInDays = Math.floor((t1-t2)/(24*3600*1000));
// 24*3600*1000 is milliseconds in a day
console.log(diffInDays);
// Send email
MailApp.sendEmail({
to:mail ,
subject: subjectMail,
htmlBody:htmlformail,
});
}
I'm not confident on the new_data.push([resource_col,status_col,due_date_col,link_col]), it's seems to be corect but I have no no way to verify that
Anyway thanks for using the utils script at https://github.com/SolannP/UtilsAppSsript, glad to see it help 👍
I am trying to trace email status with using inline image in an email.
For getting response i am using following code.
// handles the get request to the server
function doGet(e) {
Logger.log(e.parameter);
var method = e.parameter['method'];
switch (method) {
case 'track':
var email = e.parameter['email'];
updateEmailStatus(email);
default:
break;
}
}
function updateEmailStatus(emailToTrack) {
// get the active spreadsheet and data in it
var id = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet = SpreadsheetApp.openById(id).getActiveSheet();
var data = sheet.getDataRange().getValues();
// get headers
var headers = data[0];
var emailOpened = headers.indexOf('status') + 1;
// declare the variable for the correct row number
var currentRow = 2;
// iterate through the data, starting at index 1
for (var i = 1; i < data.length; i++) {
var row = data[i];
var email = row[0];
if (emailToTrack === email) {
// update the value in sheet
sheet.getRange(currentRow, emailOpened).setValue('opened');
break;
}
currentRow++;
}
}
Here is the sheet
it works in a stand alone file but not working in a addon script project. Is there any way to trace out the send email using apps script ?
Any help on this issue will be highly appreciated. Thank you
I have solved the issue. I have change the code little bit and create a new draft as more than one inline image was added to the existing draft.
The change is here
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Email_Status');
After this few changes i deployed as new webapp and it started working. Thank you for contribution
Try this:
//var id = SpreadsheetApp.getActiveSpreadsheet().getId(); remove this
var sheet = SpreadsheetApp.openById(id);//change this by hardcoding the id
I'm new to Google Apps script and am trying to add an image inline to an automated response email.
The auto reply works perfectly, the main text of the email formats well in plain text and html.
the problem i'm facing is that the image does not appear.
my code:
// This constant is written in column Y for rows for which an email
// has been sent successfully.
var EMAIL_SENT = 'EMAIL_SENT';
/**
* Sends non-duplicate emails with data from the current spreadsheet.
*/
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(sheet.getSheetByName('Data'))
var startRow = 2; // First row of data to process
// Fetch the range
var dataRange = sheet.getRange("L2:L1000")
var dataRange2 = sheet.getRange("K2:K1000")
var dataRange3 = sheet.getRange("O2:O1000")
var dataRange4 = sheet.getRange("Y2:Y1000")
var dataRange5 = sheet.getRange("B2:B1000")
// Fetch values for each row in the Range.
var data = dataRange.getValues();
var data2 = dataRange2.getValues();
var data3 = dataRange3.getValues();
var data4 = dataRange4.getValues();
var data5 = dataRange5.getValues();
for (var i = 0; i < data.length; ++i) {
var yesno = data2[i]
if(yesno == "Yes"){
var TFlogoUrl = "https://drive.google.com/openid=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";
var TFlogoBlob = UrlFetchApp
.fetch(TFlogoUrl)
.getBlob()
.setName("TFlogoBlob");
var emailAddress = data[i];
var ShipID = data3[i];
var cmdrID = data5[i];
var TFmsg = "Hi " + cmdrID + ",/n /nThank you for signing up to The Fatherhoods Lost Souls Expedition./n /nYour unique Ship ID is: " + ShipID + "/n /nWe look forward to seeing you on the expedition CMDR!/n /nFly Safe,/nThe Lost Souls Expedition team.";
var htmlTFmsg = "Hi " + cmdrID + ",<br> <br>Thank you for signing up to The Fatherhoods Lost Souls Expedition.<br> <br>Your unique Ship ID is: " + ShipID + "<br> <br>We look forward to seeing you on the expedition CMDR!<br> <br>Fly Safe,<br>The Lost Souls Expedition team.<br><img src='cid:TFlogo'>";
emailSent = data4[i]; // email sent (column Y)
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
var subject = "Lost Souls Expedition Sign up confirmation";
MailApp.sendEmail(emailAddress,subject,TFmsg,{
htmlBody: htmlTFmsg,
inlineImage:
{
TFlogo:TFlogoBlob
}
});
sheet.getRange("Y" + (startRow + i)).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
}
How about this modification?
Modification points:
You cannot retrieve the file blob from this URL var TFlogoUrl = "https://drive.google.com/openid=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";. If you want to retrieve the file blob from URL, please use var TFlogoUrl = "http://drive.google.com/uc?export=view&id=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";. 1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287 is the file ID.
As an another method, from the file ID, it is found that the values of getSharingAccess() and getSharingPermission() are ANYONE_WITH_LINK and VIEW, respectively. So you can also retrieve the blob using var TFlogoBlob = DriveApp.getFileById("1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287").getBlob().setName("TFlogoBlob");. I recommend this.
When you want to use the inline image to email, please modify from inlineImage to inlineImages.
The script which reflected above points is as follows.
Modified script:
Please modify your script as follows.
From:
var TFlogoUrl = "https://drive.google.com/openid=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";
var TFlogoBlob = UrlFetchApp.fetch(TFlogoUrl).getBlob().setName("TFlogoBlob");
To:
var id = "1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";
var TFlogoBlob = DriveApp.getFileById(id).getBlob().setName("TFlogoBlob");
And
From:
inlineImage: {TFlogo:TFlogoBlob}
To:
inlineImages: {TFlogo:TFlogoBlob}
References:
sendEmail(recipient, subject, body, options)
If I misunderstand your question, please tell me. I would like to modify it.
I'm in the process of learning scripted REST API's. I have one that creates a REQ and RITM when the user does a POST. I'm having trouble populating variables from the rest post to the RITM. Below is my current code. Response is the RITM, Requester, and short description. I'm open to all suggestions, like I said I'm learning this on the fly, so if there is any glaring problems, I'm all ears. Thanks!
(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
var cartId = GlideGuid.generate(null);
var cart = new Cart(cartId);
var item = cart.addItem('25409830135aa20099fc7e776144b0a0');
var rc = cart.placeOrder();
var req = request.getHeader('ContactEmployeeId');
var sdesc = request.getHeader('ShortDescription');
//return rc.number;
//gs.addInfoMessage(rc.number);
var num = rc.sys_id; //get sys ID of newly created request
var rnum = 0;
//using the request number, query the RITM table for related RITM
var u = new GlideRecord('sc_req_item');
u.addEncodedQuery('request='+num);
u.query();
while ( u.next() )
{
rnum = u.number;
}
response.setBody({
Requested_Item: rnum,
u_requester: req,
short_description: sdesc
});
response.setContentType('application/json');
})(request, response);
You can use the setVariable(ritm, variableName, value) method such as this.
var cartId = GlideGuid.generate(null);
var cart = new Cart(cartId);
var item = cart.addItem('25409830135aa20099fc7e776144b0a0');
// add your variables here to the item variable in your cart object
cart.setVariable(item, "comments", message);
cart.setVariable(item, "my_var_1", value1);
cart.setVariable(item, "my_var_2", value2);
// submit order
var rc = cart.placeOrder();