Post # characters in URL being encoded by HtmlService - google-apps-script

I am having a problem building links to my Zendesk instance.
In my script, I pull some ticket information from Zendesk and display it in a web app for some important people. I the table of tickets, I want to include a link to the ticket in Zendesk. In the code, I set the value of the cell at such.
var cell = "<td>" + ticket.subject + "</td>";
However, in the resulting webapp the link shows up as follows:
https://mydomain.zendesk.com/agent#%2ftickets%2f1507
This link doesn't work. I have checked the string before sending it to the HtmlService, and I don't see anything in the Caja documentation.
Thanks
This code causes the same problem:
function doGet() {
var html = '<html><body><table><tr><th>A Header</th></tr><tr><td>aoeuaoue</td></tr></table>';
html += '</body></html>';
Logger.log(html);
return HtmlService.createHtmlOutput(html);
}

Related

Deployment ID in URL changes when app script runs causing the script to fail, how can I make the URL use the correct Deployment ID?

I'm using a script to create an annual leave request workflow that begins with a google form, collects responses in a sheet, then emails a manager for approval, then emails the requester with either an Approved/Denied confirmation email. The script runs and sends the email to the manager, but once either the approve or deny button is pressed, the URL generated uses a deployment ID that does not match the version of either the current /exec
or the /dev version.
Here is the code snippet for the section that should run when the buttons are used:
function SheetHandler(sheet) {
var _sheet = sheet;
var _data = getRowsData(_sheet);
var _markPending = function(d) {
d.state = PENDING_STATE;
d.identifier = Utils.generateUUID();
manager_email = d[SETTINGS.MANAGERS_EMAIL_COLUMN_NAME].match(EMAIL_REGEX);
var scriptUri = ScriptApp.getService().getUrl();
// hack some values on to the data just for email templates.
d.approval_url = scriptUri + "?i=" + d.identifier + '&state=' + APPROVED_STATE;
d.deny_url = scriptUri + "?i=" + d.identifier + '&state=' + DENIED_STATE;
d.manager_email = manager_email
message = Utils.processTemplate(SETTINGS.PENDING_MANAGER_EMAIL, d);
subject = Utils.processTemplate(SETTINGS.PENDING_MANAGER_EMAIL_SUBJECT, d);
MailApp.sendEmail(manager_email,subject,"",{ htmlBody: message });
setRowData(_sheet, d);
}
Is there another way to get the correct deployment url for this?
I've tested it by copying the Head and Version deployment ID into the URL generated by the approve/deny buttons in the emails, if I copy the correct ID from the Deploy menu into the URL in place of the incorrect one then the remaining code executes as expected.
The link looks like this:
https://script.google.com/a/macros//s//exec?i=6b843ea2-7b2b-454a-ff2e-89bc9a54d48e&state=APPROVED

How to obtain initial OAuth2.0 code from browser?

I have made a javascript script in Google Apps Script, attached to a google sheet. I ultimately want to connect the Google Sheet to the Google Fit API and have my fitness data automatically inputted to the Google Sheet. At step 0, I made my Google Console project and OAuth2.0 client ID & secret. I am at step 1, where I need to obtain the authentication code from the initial 'GET' request.
My request is correct and I can send the request correctly using the callback notation; the code below is run in a callback in a timed for loop such that the html object (html_objet) remains active for a certain amount of time, waiting to get the code. I can see the code in the browser url when I have finished approving with the Google popup, but I do not know how to import this code value from the client browser(popup) into my javascript program. I open the client browser(popup) using :
var html_texte = '<html><head><script>'
+ 'const winRef = window.open("'+js2html_data+'");'
+ 'winRef ? google.script.host.close() : window.alert("Allow popup to redirect to url");'
+ 'window.onload=function(){document.getElementById("'+js2html_data+'").href ="'+js2html_data+'";};'
+ '</script></head><body>'
+ '</body></html>';
var html_objet = HtmlService.createHtmlOutput(html_texte).setWidth(90).setHeight(1);
html_objet.js2html_data = js2html_data;
SpreadsheetApp.getUi().showModalDialog(html_objet, "Opening ...");
This works. But, I can not do anything with the window once it is open (ie: reload the window, get the current url).
I tried modifying the html_texte variable to the text below, such that I can return the url of the authenticated page. It does not work, how can I update the js2html_data variable such that it shows the url of the final Google user authenticated page? Or, pass the url to another html variable (html2js_data) out to my javascript program?
var html_texte = '<html><head><script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>'
+ '<script>'
+ 'const winRef = window.open("'+js2html_data+'");'
+ 'winRef ? google.script.host.close() : window.alert("Allow popup to redirect to url");'
+ 'window.onload=function(){document.getElementById("'+js2html_data+'").href ="'+js2html_data+'";};'
// + '$(document).ready(function getUrl(){ document.getElementById("'+html2js_data+'").innerHTML=window.location.href; });'
+ '$(document).ready(function getUrl(){ document.getElementById("'+html2js_data+'").href=window.location.href; });'
//+ '$(document).ready(function getUrl(){ document.getElementById(<?="'+html2js_data+'"?>).href=window.location.href; });'
+ '</script></head><body>'
// + '<h3 id="html2js_data" onclick="getUrl()">OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO</h3>'
+ '<div id="html2js_data"></div>'
+ '</body></html>';
Any suggestions would be great...I tried a lot of things...

MailApp sendEmail htmlBody clickable dynamic link

I wrote a script that creates a new Spreadsheet from one of the Sheets of the original Spreadsheet and emails the new Spreadsheet with the PDF version attached and has an html body with some text and the link to the new Spreadsheet. The script fires each morning because the Sheet has dynamically chaning data, so the link also changes with every trigger.
The problem is that the link in the html body appears as a text and I would like it to be clickable. I tried formatting it with with A HREF but that wouldn't seem to do the trick
var napijelentes = SpreadsheetApp.create(fajlnev);
var napijelentesfajlid = napijelentes.getId();
var napijelentesfajl = DriveApp.getFileById(napijelentesfajlid);
var napijelentesurl = napijelentes.getUrl();
MailApp.sendEmail({
to: ellenorzes,
subject: subject,
htmlBody: "To download the spreadsheet please follow the link below: <br>" + napijelentesurl + "<br><br>",
attachments: [napijelentesfajl]
});
This way the link appears in the email as plain text, with [napijelentesurl] in front of it and is still not clickable.
Any solutions to my problem?
Create a variable for the html string.
var h;
h = 'To download <br><a href = "' + napijelentesurl + '">' +
napijelentesurl + "</a><br><br>";
Use single quotes on the ends of string that need double quotes inside the string.

How to add "Edit Response" link to Google Forms emails?

I have a simple Google Form that collects data, and, using AppScript, sends confirmation emails to users who fill it out. After user submits the form, on confirmation, s/he will see a link to edit his/her response.
I'd like to include that link as a part of the confirmation email (Right now, it only shows up on the page.) How can I obtain the URL to edit a submitted response?
I am able to get the link to the Form through SpreadsheetApp.getActiveSpreadsheet().getFormUrl(). It gives me the following format: https://docs.google.com/a/domain.com/spreadsheet/viewform?formkey=<formKey>
The link however doesn't include the edit key, which is required for users to edit his/her response. The expected URL should look like this: https://docs.google.com/a/domain.com/spreadsheet/viewform?formkey=<formKey>&edit=<editKey>
Thanks for the help in advance!
-K
Edited:
Added a feature request on this: http://code.google.com/p/google-apps-script-issues/issues/detail?id=1345&thanks=1345&ts=1337773007
The answer that this wasn't possible by #Henrique Abreu was true until very recently. Google seems to have added getEditResponseUrl() to the FormResponse class and with that it becomes possible to use code like this to get the edit URL for a bunch of existing forms:
function responseURL() {
// Open a form by ID and log the responses to each question.
var form = FormApp.openById('1gJw1MbMKmOYE40Og1ek0cRgtdofguIrAB8KhmB0BYXY'); //this is the ID in the url of your live form
var formResponses = form.getResponses();
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
Logger.log(formResponse.getEditResponseUrl());
}
}
To make it automatically email the user as they respond one could add a trigger on form submit. As The situation I'm working with doesn't require people to log in with an apps account I don't have access to an email address automatically so I have a text question that captures the user's email address.
It does ask the question about whether or not editing the forms is what you want. I've been grappling with the relative advantages of editing an existing response or sending a prefilled form using toPrefilledUrl() so that I can see how things have changed over time. I guess this comes down to the value that tracking this will provide you.
If you are using Google Apps your responders can edit there form responses.
See: How to Edit Form Responses
--edit this is now possible. See other answers.
After user submits the form, on confirmation, s/he will see a link to
edit his/her response. I'd like to include that link as a part of the confirmation email
That is not possible, period.
That link is not accessible anywhere and one can't guess/construct it. But, there's some workarounds that might suit you (some suggested here that I'll re-phrase), e.g.
Send a per-populated form link and have the user re-send it. You'd need to have some kind of control field (e.g. the username), so you can know and delete/ignore his older submits. Possibly automatically via a script.
You could also develop and publish an apps-script GUI and send a link to this apps script plus a parameter that you generate where you can determine which entry you should edit. The down-side of this approach is that it's somewhat cumbersome and overkill to re-design the whole form on Apps Script. But again, it works.
At last, you could open an "Enhancement Request" on Apps Script issue tracker and wait until they and Google Spreadsheet/Forms team get together to develop a solution.
Here is a clear blog post that shows you how to do it step by step and explains what's going on under the hood for AppsScripts newbies:
http://securitasdato.blogspot.com/2014/11/sending-confirmation-emails-from-google.html
While collectively you can get there from the all the excellent answers provided here, the script from that post worked best for me.
Does this help - I haven't tried it but I was looking for the same thing a while ago and noticed this.
From this page
https://developers.google.com/apps-script/reference/forms/
code from there contains this:
Logger.log('Published URL: ' + form.getPublishedUrl());
Logger.log('Editor URL: ' + form.getEditUrl());
Jon
Great, script works! Thanks.
For newbies, like me: Just paste the andre's code for function SendConfirmationMail(e) into your spreadsheet's code editor and set 'on form submit' trigger to run it. That's in spreadsheet script editor, not form script editor.
You need to hack in some values. Read the code. For me the confusing one was the need to replace the ********COLUMN SEQUENCE EX 14****** with the sheet column number where you want the edit urls to end up. I used 39 which is one column more than my form was using up.
However, I got runtime probs in this part:
for (var i in headers) {
value = e.namedValues[headers[i]].toString();
// Do not send the timestamp and blank fields
if ((i !== "0") && (value !== "")) {
message += headers[i] + ' :: ' + value + "<br>";
}
}
Dunno why, but I replaced it with this:
for (var keys in columns) {
var key = columns[keys];
if ( e.namedValues[key]) {
message += key + ' :: '+ e.namedValues[key] + "<br>";
}
}
Works for me.
Try This: (Credits is not for me, because i merge two solutions of the third part)
Source: Send Confirmation Email with Google Forms
/* Send Confirmation Email with Google Forms */
function Initialize() {
var triggers = ScriptApp.getScriptTriggers();
for (var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendConfirmationMail")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendConfirmationMail(e) {
var form = FormApp.openById('***YOUR FORM CODE***');
//enter form ID here
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('***SHEET NAME***');
//Change the sheet name as appropriate
var data = sheet.getDataRange().getValues();
var urlCol = ***************COLUMN SEQUENCE EX 14******; // column number where URL's should be populated; A = 1, B = 2 etc
var responses = form.getResponses();
var timestamps = [], urls = [], resultUrls = [], url;
for (var i = 0; i < responses.length; i++) {
timestamps.push(responses[i].getTimestamp().setMilliseconds(0));
urls.push(responses[i].getEditResponseUrl());
}
for (var j = 1; j < data.length; j++) {
resultUrls.push([data[j][0]?urls[timestamps.indexOf(data[j][0].setMilliseconds(0))]:'']);
url = resultUrls[i-1]
}
sheet.getRange(2, urlCol, resultUrls.length).setValues(resultUrls);
try {
var ss, cc, sendername, subject, headers;
var message, value, textbody, sender;
// This is your email address and you will be in the CC
cc = Session.getActiveUser().getEmail();
// This will show up as the sender's name
sendername = "****YOUR NAME******";
// Optional but change the following variable
// to have a custom subject for Google Docs emails
subject = "Registro de Oportunidade submetido com sucesso";
// This is the body of the auto-reply
message = "Nós recebemos seu registro de oportunidade.<br>Muito Obrigado!<br><br>";
ss = SpreadsheetApp.getActiveSheet();
headers = ss.getRange(1, 1, 1, ss.getLastColumn()).getValues()[0];
// This is the submitter's email address
sender = e.namedValues["********COLUMN NAME OF DESTINATION E-MAIL************"].toString();
for (var i in headers) {
value = e.namedValues[headers[i]].toString();
// Do not send the timestamp and blank fields
if ((i !== "0") && (value !== "")) {
message += headers[i] + ' :: ' + value + "<br>";
}
}
message += "<br>Link to edit" + ' :: ' + url + "<br>";
textbody = message.replace("<br>", "\n");
GmailApp.sendEmail(sender, subject, textbody,
{cc: cc, name: sendername, htmlBody: message});
} catch (e) {
Logger.log(e.toString());
}
}
you can try to populate a form with the values given from that email address than delete previous answers ...
it's not a beautiful way but it can works ...
I don't think we have access to what that value is through the Spreadsheet API (which means Apps Script doesn't have it either). The closest I can think of would be the "key" value in this feed. You'd have to test to find out though. There's no other alternative that I know of other than accessing the Spreadsheet API directly. So first, you'd have to get the last row through the api use ?reverse=true&max-results=1

How do I send an HTML Form in an Email .. not just MAILTO

I have an HTML form for people to fill out, and I want it so when they click the submit button, it will just send the email, not bring up their email and ask them to send the message themselves.
When I use:
<form action="MAILTO:emailaddress#email.com"... >
All that does is open up a new window and populates the body of the email, but I want it to just send an email.
And is there a way to format the output of what the email will look like? Instead of just a list of the field names and the entered value.
Thanks.
> 2021 Answer = Easy Way using GMail (5 Mins)
We had a similar challenge to solve yesterday, and we solved it using a Google Apps Script!
Send Email From an HTML Form Without a Backend (Server) via Google!
The solution takes 5 mins to implement and I've documented with step-by-step instructions: https://github.com/nelsonic/html-form-send-email-via-google-script-without-server
Brief Overview
A. Using the sample script, deploy a Google App Script
Deploy the sample script as a Google Spreadsheet APP Script:
google-script-just-email.js
remember to set the TO_ADDRESS in the script to where ever you want the emails to be sent.
and copy the APP URL so you can use it in the next step when you publish the script.
B. Create your HTML Form and Set the action to the App URL
Using the sample html file:
index.html
create a basic form.
remember to paste your APP URL into the form action in the HTML form.
C. Test the HTML Form in your Browser
Open the HTML Form in your Browser, Input some data & submit it!
Submit the form. You should see a confirmation that it was sent:
Open the inbox for the email address you set (above)
Done.
Everything about this is customisable, you can easily
style/theme the form with your favourite CSS Library
and Store the submitted data in a Google Spreadsheet
for quick analysis.
The complete instructions are available on GitHub:
https://github.com/nelsonic/html-form-send-email-via-google-script-without-server
You are making sense, but you seem to misunderstand the concept of sending emails.
HTML is parsed on the client side, while the e-mail needs to be sent from the server. You cannot do it in pure HTML. I would suggest writing a PHP script that will deal with the email sending for you.
Basically, instead of the MAILTO, your form's action will need to point to that PHP script. In the script, retrieve the values passed by the form (in PHP, they are available through the $_POST superglobal) and use the email sending function (mail()).
Of course, this can be done in other server-side languages as well. I'm giving a PHP solution because PHP is the language I work with.
A simple example code:
form.html:
<form method="post" action="email.php">
<input type="text" name="subject" /><br />
<textarea name="message"></textarea>
</form>
email.php:
<?php
mail('youremail#example.com', $_POST['subject'], $_POST['message']);
?>
<p>Your email has been sent.</p>
Of course, the script should contain some safety measures, such as checking whether the $_POST valies are at all available, as well as additional email headers (sender's email, for instance), perhaps a way to deal with character encoding - but that's too complex for a quick example ;).
I actually use ASP C# to send my emails now, with something that looks like :
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form.Count > 0)
{
string formEmail = "";
string fromEmail = "from#email.com";
string defaultEmail = "default#email.com";
string sendTo1 = "";
int x = 0;
for (int i = 0; i < Request.Form.Keys.Count; i++)
{
formEmail += "<strong>" + Request.Form.Keys[i] + "</strong>";
formEmail += ": " + Request.Form[i] + "<br/>";
if (Request.Form.Keys[i] == "Email")
{
if (Request.Form[i].ToString() != string.Empty)
{
fromEmail = Request.Form[i].ToString();
}
formEmail += "<br/>";
}
}
System.Net.Mail.MailMessage myMsg = new System.Net.Mail.MailMessage();
SmtpClient smtpClient = new SmtpClient();
try
{
myMsg.To.Add(new System.Net.Mail.MailAddress(defaultEmail));
myMsg.IsBodyHtml = true;
myMsg.Body = formEmail;
myMsg.From = new System.Net.Mail.MailAddress(fromEmail);
myMsg.Subject = "Sent using Gmail Smtp";
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential("testing#gmail.com", "pward");
smtpClient.Send(defaultEmail, sendTo1, "Sent using gmail smpt", formEmail);
}
catch (Exception ee)
{
debug.Text += ee.Message;
}
}
}
This is an example using gmail as the smtp mail sender. Some of what is in here isn't needed, but it is how I use it, as I am sure there are more effective ways in the same fashion.