email a docx file with googlescript - javascript

I'm only a beginner with using google script, so please be kind if this is a very stupid question :)
My script currently e-mails a pdf, created from a google drive file like this:
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
I'd like to also e-mail a docx file, but of course it's less easy.
I found one way to do this:
Using Google Script to send an email with a Word doc attachment
... but it seems to use an old solution which no longer works. Code:
var url = 'https://docs.google.com/feeds/';
var doc = UrlFetchApp.fetch(url+'download/documents/Export?exportFormat=doc&format=doc&id='+copyId,
googleOAuth_('docs',url)).getBlob();
Error:
Execution failed: ReferenceError: "googleOAuth_" is not defined.
Am I using the right method but with a mistake, or is there a better method to export a docx?
Thanks very much for your help and patience!

If you are still looking for the solution, how about this answer? In order to convert Google Document to docx and export docx, please use access token. In your case, you can use ScriptApp.getOAuthToken() for the access token. So how about the following modification?
From :
var url = 'https://docs.google.com/feeds/';
var doc = UrlFetchApp.fetch(url+'download/documents/Export?exportFormat=doc&format=doc&id='+copyId,
googleOAuth_('docs',url)).getBlob();
To :
var url = "https://docs.google.com/feeds/download/documents/export/Export?id=" + copyId + "&format=docx&access_token=" + ScriptApp.getOAuthToken();
var docx = UrlFetchApp.fetch(url).getBlob();
Note :
You can use the access token as a query parameter.
In your question, you want a docx file. But in your script, it seems that you want a doc file.
In this modification, the docx is used. If you want a doc file, please modify it.
At the modified script, docx is the blob of docx. Please use this instead of pdf of your script.
If I misunderstand your question, I'm sorry.
Updated: February 7, 2020
From January, 2020, the access token cannot be used with the query parameter like access_token=###. Ref So please use the access token to the request header instead of the query parameter. It's as follows.
var res = UrlFetchApp.fetch(url, {headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}});

Related

Azure Server failed to authenticate the request. Make sure the value of the authorization header is formed correctly including the signature

enter code hereI am trying to download the file stored in azure blob using javascript and getting this error.
Here is my code
function getUrlOfAttachmentFileFromBlob(new_fileurl,new_fileName) {
var fileHyperlink = '';
var blobUri = 'https://' + 'Storage_Account_Name' + '.blob.core.windows.net';
var containerName = 'trial';
var sas_token = 'sastoken' ;
var blobService = AzureStorage.Blob.createBlobServiceWithSas(blobUri, sas_token);
//.withFilter(new AzureStorage.Blob.ExponentialRetryPolicyFilter());
var downloadLink = blobService.getUrl(new_fileName, new_fileurl.replace('/'+containerName+'/',''), sas_token);
if (downloadLink != null)
{
alert("Link " + downloadLink);
downloadURI(downloadLink, new_fileName);
}
}
I am not generating shared signature and sas token here. I am directly assigning the sas token to the variable.
When I try to open the link in browser I am getting this error
AuthenticationFailed</Code><Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
RequestId:504f2ef5-f01e-0021-0e02-74e194000000
Time:2021-07-08T14:09:47.9951927Z</Message><AuthenticationErrorDetail>sp is mandatory. Cannot be empty</AuthenticationErrorDetail></Error>
I am not passing any headers in my code.
What i am missing here?
SAS Token =
?sp=r&st=2021-07-08T12:19:08Z&se=2021-07-08T20:19:08Z&spr=https&sv=2020-02-10&sr=c&
Without sig part.
This is what I am getting from geturl function =
?%3Fsv=2020-02-10&ss=bfqt&srt=sco&sp=rwdlacuptfx&se=2021-07-11T12%3A30%3A23Z&st=2021-06-11T04%3A30%3A23Z&spr=https%2chttp&
I think I am not getting correct url from this function, so i replaced that line with this
const downloadLink = blobUri +'/' + containerName + '/' + new_fileName + sas_token;
But still not able to download the file. But not getting authentication error.
Thank you...
The reason you're getting this error is because your SAS token is not valid. If you look closely at the error message you will see the following:
<AuthenticationErrorDetail>sp is mandatory. Cannot be empty</AuthenticationErrorDetail>
Essentially your SAS token is missing signed permissions (sp) parameter. Please check your SAS token and make sure that it is correctly formed.
I resolve the related issues on shared access signature (SAS)
Allowed resource types by clicking
Service
Container
Object
and finally generate new token works fine.

Postman - Get only endpoint from a URL

Having this kind of endpoing:
https://hey.com/p1/m/p2
I want to get rid of the https://hey.com and get only the /p1/m/p2 part on the Pre-request Script. I know I can do it using request.url.replace(/^.*\/\/[^\/]+/, ''), getting the desired output /p1/m/p2.
Is there any other way to do it without using replace or regex? Something like request.url.pathname (which is not working, obviously).
The URL above is just an example, the endpoints and urls will vary.
Bear in mind that I'm using the Pre-request Script on the Postman environment and some things may not work.
Thank you so much.
You should be able to use the URL browser API to construct a URL object.
(new URL(request.url)).pathname
If you're using the desktop version, you can use the built-in node.js API.
var URL = require('url');
URL.parse(request.url).pathname
You can try something like this
var fullUrl = request.url.split('/');
fullUrl.splice(0,3);
var url = a.join('/');
console.log(url);

Thunderbird extension: open EML file as draft

After my first question here, I am now looking for a way do the the same, but instead of opening an EML as a message, I want to open it as a draft.
Basically, I want to load a generated EML file into the compose window, so I can directly send it.
I already found some code, but I can't find the correct documentation on how to use it
var filePath = new FileUtils.File(getPath(params));
var uri = io.newFileURI(filePath);
var msgComposeService = Components.classes["#mozilla.org/messengercompose;1"].getService(Components.interfaces.nsIMsgComposeService);
var messenger = Components.classes["#mozilla.org/messenger;1"].createInstance(Components.interfaces.nsIMessenger);
var hdr = messenger.msgHdrFromURI(uri.spec);
var identity = getIdentityForHeader(hdr, Components.interfaces.nsIMsgCompType.Draft);
var msgWindow = Components.classes["#mozilla.org/messenger/msgwindow;1"].createInstance(Components.interfaces.nsIMsgWindow);
msgComposeService.OpenComposeWindow(null,null,uri,Components.interfaces.nsIMsgCompType.Draft,Components.interfaces.nsIMsgCompFormat.Default,identity,msgWindow);
I would suggest injecting the eml file into a local Drafts folder so as to get an nsIMsgDBHdr, and then calling the ComposeMessage function with Ci.nsIMsgCompType.Draft, Ci.nsIMsgCompFormat.Default, yourMsgHdr.folder, yourMsgHdr'sURI.
I think there are several StackOverflow answers on how to inject a given message into a folder.

Javascript: how to append data to a file

how can i append data to a file using javascript?
i tried to use this code, but i got an error:
var fso = new ActiveXObject("Scripting.FileSystemOject");
var filepath = fso.GetFile("member.txt");
var fileObject = fso.OpenTextFile(filepath, 8);
file.WriteLine(id + "|" + pass);
fileObject.close();
the error is on var fso = new ActiveXObject("Scripting.FileSystemOject");, written: Error: Automation server can't create object
is there any other way to append the file using javascript or the way to fix this? thanks :)
EDIT:
i have doing what's written on this, and it still not working :/
I just realized these in your code:
var fileObject = fso.OpenTextFile(filepath, 8,true);
You'll need the true-argument, if the file does not exist, or you want to overwrite/append it.
var filepath = fso.GetFile("member.txt");// This won't work.
var filepath = "your_filePath"; // Use this instead
var fileObject = fso.OpenTextFile(filepath, 8, true);
OpenTextFile() needs a path as a string like "D:/test/file.txt". GetFile() returns an object, which you can see as a string (D:\test\file.txt), but it's not a string. Use also absolute paths, relative paths don't seem to work by my experience.
EDIT
Add the code below to the <head>-part of your html-file, then save locally as a hta (with file extension hta, not htm or html).
<hta:application
applicationName="MyApp"
id="myapp"
singleInstance="yes"
/>
Then run the hta-file. If you still getting an ActiveX-error, it's not supported by your OS. If this works, you haven't done all the security settings correct.
EDIT II
In this case it's not very usefull to get the path through ActiveX, you'll need to write it literal anyway. And I'm not supposed to do your homeworks, but this does the trick...
var filepath = new String(fso.GetFile("member.txt")).replace(/\\/g,'/');
And don't forget what I've said above about using absolute paths...
The 8 in the OpenTextFile function specify that you want to append to the file. Your problem comes from the security restriction of your browser. To make it work you'll have to lower the security level, which is not really recommended.
The error is thrown because there are security restrictions which donot allow the activex to run. change your security settings to allow the activex if your using internet explorer (which i think you are).
This might be useful http://windows.microsoft.com/en-US/windows/help/genuine/ie-activex
Cheers
EDIT: i have doing what's written on this, and it still not working :/
* try Restarting your browser
As pointed out in this comment
Javascript: how to append data to a file
the cause of the error Error: Automation server can't create object is the typo in the progid passed to ActiveXObject: Oject instead of Object:
var fso = new ActiveXObject("Scripting.FileSystemOject");
there is a missing b!

Reading image capture files in PhoneGap

I'm working on a PhoneGap application that captures images using the camera and, later, uploads them. There are two modes of operation for camera in PhoneGap: raw base64 encoded data or a file URI.
The docs themselves say:
Note: The image quality of pictures taken using the camera on newer
devices is quite good. Encoding such images using Base64 has caused
memory issues on some of these devices (iPhone 4, BlackBerry Torch
9800). Therefore, using FILE_URI as the 'Camera.destinationType' is
highly recommended.
So I'm keen to use FILE_URI option. This works great and you can even show the images in IMG tags. The URL looks like this:
file://localhost/var/mobile/Applications/4FE4642B-944C-449BB-9BD6-1E442E47C7CE/tmp/photo_047.jpg
However, at some point later I want to read the contents of the file to upload to a server. I was going to do this using the FileReader type. This doesn't work and I think it's because I can't access the file at the URL above.
The error code I get back from readDataUrl is 1 > FileError.NOT_FOUND_ERR = 1;
Any ideas how I can get to the file? I tried just accessing the last part of the path (photo_047.jpg) based on another sample I saw but no luck.
I'm just getting started with PhoneGap, and given the age of this question you may have found an answer already, but I'll give it a try anyway.
First, would you be able to use the built-in FileTransfer object? It takes a file: URI as an argument.
If FileTransfer won't work for you, and you need to read the file data yourself, you'll need the PhoneGap File objects, like FileReader , as you said. But most of those expect a plain pathname -- not a URI -- to specify the file to work with. The reason you're getting NOT_FOUND_ERR is because it's trying to open a file named file:/localhost/var....
Here's a quick one-liner to extract the path part from your URI:
var path = /file:\/\/.*?(\/.*)/.exec(fileuri)[1];
Hope this helps!
The answer from jgarbers was of help to me but it did not solve the problem. I realized the camera stores photos in Temp folder instead of Document folder. Setting my local file system to temporary allowed it to find the correct location for the camera images.
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, ...
...
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, ...
...
var path = /file://.?(/.)/.exec(fileuri)[1];
Ref. above jgarbers and Rik answers (solution has been tested successfully on iOs 7)
you can user the file transfer plugin for uploading any file to the server.
//// pass your file uri to the mediafie param
function uploadFile(mediaFile) {
var ft = new FileTransfer();
path = mediaFile.fullPath;
name = mediaFile.name;
////your service method url
var objUrl = http://example.com;
ft.upload(path,
objUrl,
function (result) {
alert("Success");
},
function (error) {
alert('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}

Categories