I had a wild idea that I could build a website blog for an unsophisticated user friend using Google Drive Documents to back it. I was able to create a contentService that compiles a list of documents. However, I can't see a way to convert the document to HTML. I know that Google can render documents in a web page, so I wondered if it was possible to get a rendered version for use in my content service.
Is this possible?
You can try this code :
function getGoogleDocumentAsHTML(){
var id = DocumentApp.getActiveDocument().getId() ;
var forDriveScope = DriveApp.getStorageUsed(); //needed to get Drive Scope requested
var url = "https://docs.google.com/feeds/download/documents/export/Export?id="+id+"&exportFormat=html";
var param = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true,
};
var html = UrlFetchApp.fetch(url,param).getContentText();
Logger.log(html);
}
Node.js Solution
Using the Google APIs Node.js Client
Here's how you can get a google doc as html using google drive's node.js client library.
// import googleapis npm package
var google = require('googleapis');
// variables
var fileId = '<google drive doc file id>',
accessToken = '<oauth access token>';
// oauth setup
var OAuth2 = google.auth.OAuth2,
OAuth2Client = new OAuth2();
// set oauth credentials
OAuth2Client.setCredentials({access_token: accessToken});
// google drive setup
var drive = google.drive({version: 'v3', auth: OAuth2Client});
// download file as text/html
var buffers = [];
drive.files.export(
{
fileId: fileId,
mimeType: 'text/html'
}
)
.on('error', function(err) {
// handle error
})
.on('data', function(data) {
buffers.push(data); // data is a buffer
})
.on('end', function() {
var buffer = Buffer.concat(buffers),
googleDocAsHtml = buffer.toString();
console.log(googleDocAsHtml);
});
Take a look at the Google Drive V3 download docs for more languages and options.
Google docs currently has a function to do this.
Just download to zip(.html) and you can have a zip archive with html & image (if inserted)
I know this is not solution based on code, but its working :)
There is no direct method in GAS to get an HTML version of a doc and this is quite an old enhancement request but the workaround described originally by Henrique Abreu works pretty well, I use it all the time...
The only annoying thing in the authorization process that needs to be called from the script editor which makes it uneasy to use in a shared application (with "script unable" users) but this only happens once ;).
There is also a Library created by Romain Vialard that makes things (a bit) easier... and adds a few other interesting functions.
Here is a little snipped for the new version of goole AOuth following the idea posted by Enrique:
function exportAsHTML(){
var forDriveScope = DriveApp.getStorageUsed(); //needed to get Drive Scope requested
var docID = DocumentApp.getActiveDocument().getId();
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,
};
var html = UrlFetchApp.fetch(url,param).getContentText();
return html;
}
and then use the usual mailApp:
function mailer(){
var docbody = exportAsHTML();
MailApp.sendEmail({
to: "email#mail.com",
subject: "document emailer",
htmlBody: docbody });
}
Hope the new workaround helps
JD
You may use the solution here
/**
* Converts a file to HTML. The Advanced Drive service must be enabled to use
* this function.
*/
function convertToHtml(fileId) {
var file = Drive.Files.get(fileId);
var htmlExportLink = file.exportLinks['text/html'];
if (!htmlExportLink) {
throw 'File cannot be converted to HTML.';
}
var oAuthToken = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(htmlExportLink, {
headers:{
'Authorization': 'Bearer ' + oAuthToken
},
muteHttpExceptions: true
});
if (!response.getResponseCode() == 200) {
throw 'Error converting to HTML: ' + response.getContentText();
}
return response.getContentText();
}
Pass as fileId, the id of the google doc and to enable advanced drive services follow the instructions here.
I've had this problem as well. The HTML that the Document HTML Export spits out is really ugly, so this was my solution:
/**
* Takes in a Google Doc ID, gets that doc in HTML format, cleans up the markup, and returns the resulting HTML string.
*
* #param {string} the id of the google doc
* #param {boolean} [useCaching] enable or disable caching. default true.
* #return {string} the doc's body in html format
*/
function getContent(id, useCaching) {
if (!id) {
throw "Please call this API with a valid Google Doc ID";
}
if (useCaching == null) {
useCaching = true;
}
if (typeof useCaching != "boolean") {
throw "If you're going to specify useCaching, it must be boolean.";
}
var cache = CacheService.getScriptCache();
var cached = cache.get(id); // see if we have a cached version of our parsed html
if (cached && useCaching) {
var html = cached;
Logger.log("Pulling doc html from cache...");
} else {
Logger.log("Grabbing and parsing fresh html from the doc...");
try {
var doc = DriveApp.getFileById(id);
} catch (err) {
throw "Please call this API with a valid Google Doc ID. " + err.message;
}
var docName = doc.getName();
var forDriveScope = DriveApp.getStorageUsed(); // needed to get Drive Scope requested in ScriptApp.getOAuthToken();
var url = "https://docs.google.com/feeds/download/documents/export/Export?id=" + id + "&exportFormat=html";
var param = {
method: "get",
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true,
};
var html = UrlFetchApp.fetch(url, param).getContentText();
// nuke the whole head section, including the stylesheet and meta tag
html = html.replace(/<head>.*<\/head>/, '');
// remove almost all html attributes
html = html.replace(/ (id|class|style|start|colspan|rowspan)="[^"]*"/g, '');
// remove all of the spans, as well as the outer html and body
html = html.replace(/<(span|\/span|body|\/body|html|\/html)>/g, '');
// clearly the superior way of denoting line breaks
html = html.replace(/<br>/g, '<br />');
cache.put(id, html, 900) // cache doc contents for 15 minutes, in case we get a lot of requests
}
Logger.log(html);
return html;
}
https://gist.github.com/leoherzog/cc229d14a89e6327336177bb07ac2980
Perhaps this would work for you...
function doGet() {
var blob = DriveApp.getFileById('myFileId').getAsHTML();
return HtmlService.createHtmlOutput(blob);
}
Related
The user clicks on a button, which has main() assigned to it.
It runs with no errors, but the protections are not removed or applied as it seems to get stuck because of the error mentioned in the question.
Here are the functions borrowed and adapted from Stackoverflow:
// This is the main function. Please set this function to the run button on Spreadsheet.
function main() {
//DriveApp.getFiles(); // This is a dummy method for detecting a scope by the script editor.
const activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const sheetName = activeSheet.getName();
if (sheetName === 'Itens_para_Costurar') {
var token = ScriptApp.getOAuthToken()
var url = ScriptApp.getService().getUrl();
var options = {
'method': 'post',
'headers': { 'Authorization': 'Bearer ' + token },
muteHttpExceptions: true
};
UrlFetchApp.fetch(url + "&key=removeprotectListaCortadas", options); // Remove protected range
listaPecasCortadas();//Atualiza a lista de peças cortadas
SpreadsheetApp.flush(); // This is required to be here.
UrlFetchApp.fetch(url + "&key=addprotectListaCortadas", options); // Add protected range
}
}
function doGet(e) {
if (e.parameter.key == "removeprotectListaCortadas") {
var listaPecasCortadasSht = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Itens_para_Costurar'); // Please set here.
// Remove protected range.
var protections = listaPecasCortadasSht.getProtections(SpreadsheetApp.ProtectionType.RANGE);
for (var i = 0; i < protections.length; i++) {
console.log('Protection Name: ' + protections[i].getDescription())
protections[i].remove();
}
} else {
// Add protected range.
var ownersEmail = Session.getActiveUser().getEmail();
var protection = listaPecasCortadasSht.getRange('A8:J100').protect();
var editors = protection.getEditors();
for (var i = 0; i < editors.length; i++) {
var email = editors[i].getEmail();
if (email != ownersEmail) protection.removeEditor(email);
}
}
return ContentService.createTextOutput("ok");
}
I would appreciate any light towards the solution.
Modification points:
If you were using my answer, when I posted it, ScriptApp.getService().getUrl() returned the endpoint of the developer mode. But, in the current stage, it doesn't return the endpoint of the developer mode. And, in this case, the invalid endpoint is returned. Ref
In your request body, 'method': 'post', is used. But, in your script, doGet is used. I thought that this might be the reason for your current issue.
In your script, var url = ScriptApp.getService().getUrl(); is used. But, using url, you are using UrlFetchApp.fetch(url + "&key=addprotectListaCortadas", options);. In this case, the query parameter is not correct.
When these points are reflected in your script, how about the following modification?
From:
var token = ScriptApp.getOAuthToken()
var url = ScriptApp.getService().getUrl();
var options = {
'method': 'post',
'headers': { 'Authorization': 'Bearer ' + token },
muteHttpExceptions: true
};
UrlFetchApp.fetch(url + "&key=removeprotectListaCortadas", options); // Remove protected range
To:
var url = "###"; // Please manually set your Web Apps URL here.
var options = { muteHttpExceptions: true };
UrlFetchApp.fetch(url + "?key=removeprotectListaCortadas", options);
If your Web Apps is deployed as Execute the app as: Me and Who has access to the app: Anyone, when the Web Apps URL is used, the access token is not required to be used. If you want to use the developer mode, please use the access token.
Note:
This answer is for your current issue. So, I cannot check your all script. Please be careful about this.
When you modified the Google Apps Script of Web Apps, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful about this.
You can see the detail of this in my report "Redeploying Web Apps without Changing URL of Web Apps for new IDE (Author: me)".
i am trying to send the google document's content to my backend service.
In the app script i am using
if(host == 'sheets'){
var content = SpreadsheetApp.getActiveSpreadsheet().getBlob();
}else if (host == 'docs') {
var content = DocumentApp.getActiveDocument().getBlob();
}
I take the blob and sent it through multi part form request in URLFetchApp.fetch() through the payload parameter.
But the content for both the docs and sheets is converted/sent to my service as pdf.
Is there any way to preserve/send the files in google format itself ?
if not in google format then in Microsoft office formats ?
Best Regards,
Saurav
As mentioned in the similar post, this behavior is expected. If you want to get the file's content in Microsoft office formats,
you can check the following options:
(OPTION 1): Get export URL from Advanced Drive Service
Sample Code:
function getDocument(){
var host = "docs";
var fileId;
var exportFormat;
if(host == 'sheets'){
fileId = SpreadsheetApp.getActiveSpreadsheet().getId();
exportFormat = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}else if (host == 'docs') {
fileId = DocumentApp.getActiveDocument().getId();
exportFormat = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
}
var url = Drive.Files.get(fileId).exportLinks[exportFormat];
Logger.log(url);
var oauthToken = ScriptApp.getOAuthToken();
var content = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + oauthToken
}
}).getBlob();
Logger.log(content.getContentType());
content.setName("TestFile");
MailApp.sendEmail("email#sample.com", "Test", "Test", {attachments: content});
}
Pre-requisite:
You need to enable Advanced Drive Service to get the export links of the file using Drive.Files.get(). This request will return a File Resource where you can get the exportLinks that can be accessed using a key based on the supported export MIME Types
What it does?
Depending on the host set, get the file id and export format based on supported export MIME Types
Get the file resource using Drive.Files.get() and get the export link based on the export format key set in step 1.
Use UrlFetchApp.fetch(url, params) and get the file's blob using HTTPResponse.getBlob()
Output:
(OPTION 2):Create export URL manually using the template url
Sample Code:
function getDocument(){
var host = "docs";
var fileId;
var url;
if(host == 'sheets'){
fileId = SpreadsheetApp.getActiveSpreadsheet().getId();
url = "https://docs.google.com/spreadsheets/export?id="+fileId+"&exportFormat=xlsx"
}else if (host == 'docs') {
fileId = DocumentApp.getActiveDocument().getId();
url = "https://docs.google.com/feeds/download/documents/export/Export?id="+fileId+"&exportFormat=docx";
}
Logger.log(url);
var oauthToken = ScriptApp.getOAuthToken();
var content = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + oauthToken
}
}).getBlob();
Logger.log(content.getContentType());
}
What it does?
Depending on the host set, get the file id and create an export link using this templates:
EXCEL: https://docs.google.com/spreadsheets/export?id=<fileId>&exportFormat=xlsx
WORD: https://docs.google.com/feeds/download/documents/export/Export?id=<fileId>&exportFormat=docx
Use UrlFetchApp.fetch(url, params) and get the file's blob using HTTPResponse.getBlob()
Note:
Based on Quotas for Google Services, Url Fetch Call has a daily quota of 20,000 for Consumer and G Suite free edition, while 100,000 for Google Workspace accounts
I've created a script in google apps script which reads the contents of a google doc into a draft message in gmail. It doesn't, however, append the user's signature.
So my plan would be to retrieve the signature, and then append to the contents of the google doc, and then put into a draft message.
I see that there is information for retrieving a users gmail signature here: https://developers.google.com/admin-sdk/email-settings/#manage_signature_settings, but I am am having trouble trying to implement it in my existing script.
How should I proceed? (current script follows)
function doGet() {
createDraft()
return HtmlService.createHtmlOutput('<b>Your catering email template can now be found in your Drafts folder!</b>');
}
function createDraft() {
var forScope = GmailApp.getInboxUnreadCount(); // needed for auth scope
var doc = DocumentApp.openById('1fsRMxtLx3IBEYvmVy9W8uHLw3Uf2OIh4L7ZSxpkixbY');
var body = doc.getBody();
var mbody = body.getText();
var raw =
'Subject: Catering Proposal\r\n' +
'Content-Type: multipart/alternative; boundary=1234567890123456789012345678\r\n' + '\r\n' +
mbody + '\r\n' +
'--1234567890123456789012345678--\n';
var draftBody = Utilities.base64Encode(raw);
Logger.log(draftBody);
var params = {method:"post",
contentType: "application/json",
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true,
payload:JSON.stringify({
"message": {
"raw": draftBody
}
})
};
var resp = UrlFetchApp.fetch("https://www.googleapis.com/gmail/v1/users/me/drafts", params);
Logger.log(resp.getContentText());
}
I greatly appreciate any help that can be provided!
The user signature is handled by a separate API, not by the Gmail API.
You need to add the scope for this first :
https://apps-apis.google.com/a/feeds/emailsettings/2.0/
and then use GET to retrieve the signature
domain =gmail.com, for example
user = my.user, or whatever
https://apps-apis.google.com/a/feeds/emailsettings/2.0/domain/user/signature
There is an easier way to do it now covered in this post:
Apps Script to get the users signature
Basically:
var signature = Gmail.Users.Settings.SendAs.list("me").sendAs.filter(function(account){if(account.isDefault){return true}})[0].signature;
As a test case, I'm trying to copy a file from Google Drive to Dropbox using Google Scripts
function pushBuild() {
// Setup OAuthServiceConfig
var oAuthConfig = UrlFetchApp.addOAuthService("dropbox");
oAuthConfig.setAccessTokenUrl("https://api.dropbox.com/1/oauth/access_token");
oAuthConfig.setRequestTokenUrl("https://api.dropbox.com/1/oauth/request_token");
oAuthConfig.setAuthorizationUrl("https://www.dropbox.com/1/oauth/authorize");
oAuthConfig.setConsumerKey(ScriptProperties.getProperty("dropboxKey"));
oAuthConfig.setConsumerSecret(ScriptProperties.getProperty("dropboxSecret"));
var fileName = "blah.zip"
var folderName = "upload_dir"
var docs = DocsList.getFolder(folderName).find(fileName);
for(n=0;n<docs.length;++n){
if(docs[n].getName() == fileName){
var ID = docs[n].getId();
var options = {
"oAuthServiceName" : "dropbox",
"oAuthUseToken" : "always",
"method" : "put",
"payload" : docs[n].getBlob().getBytes(),
"contentType" : "application/zip"
};
var response = UrlFetchApp.fetch("https://api-content.dropbox.com/1/files_put/sandbox/upload_dir/" + fileName, options);
Logger.log(response);
}
}
}
The authorization request for the application in Dropbox appears and it tells me that I've successfully authorized my app, but when I check, the app is not in the list of "My Apps", the file has not been uploaded and there are no entries in the log. The directory "upload_dir" exists on both GD and DB. I've tried the same code with "App Folder" and "Full Dropbox" app types, but get the same result.
Additionally, running the script again once again triggers the Authorization page, similar to
to appear, clicking "Allow" then shows the success screen but the application is not listed in "My Apps". Running the script again repeats the process.
Can anyone point out what I've done wrong?
Update
So, I've now tried to implement this using the individual api calls and am still not having any success.
function testOAuth() {
var timestamp = getTimestamp();
var nonce = getNonce(timestamp);
var authString = 'OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT", oauth_signature="' + encodeURIComponent(ScriptProperties.getProperty("dropboxSecret") + '&') + '", oauth_consumer_key="' + ScriptProperties.getProperty("dropboxKey") + '"';
Logger.log(authString)
var options = {
method : "POST",
headers : {"Authorization" : authString}
}
var response = UrlFetchApp.fetch("https://api.dropbox.com/1/oauth/request_token",options);
var params = response.getContentText().split("&");
var map = new Map;
for(i = 0; i < params.length; i++){
var param = params[i].split("=");
map.put(param[0],param[1]);
}
var authStringx = "https://www.dropbox.com/1/oauth/authorize?oauth_token=" + map.get("oauth_token");
Logger.log(authStringx);
var response2 = UrlFetchApp.fetch(authStringx);
Logger.log(response2.getContentText());
var authString2 = 'OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT", oauth_token="' + map.get("oauth_token") + '" , oauth_signature="' + encodeURIComponent(ScriptProperties.getProperty("dropboxSecret") + '&' + map.get("oauth_token_secret")) + '", oauth_consumer_key="' + ScriptProperties.getProperty("dropboxKey") + '",oauth_timestamp="'+ timestamp +'", oauth_nonce="' + nonce +'"';
Logger.log(authString2);
var options3 = {
"method" : "POST",
"Authorization" : authString2
}
var response3 = UrlFetchApp.fetch("https://api.dropbox.com/1/oauth/access_token", options3);
Logger.log(response3.getContentText());
}
var getTimestamp = function(){
return (Math.floor((new Date()).getTime() / 1000)).toString()
}
var getNonce = function(timestamp){
return timestamp + Math.floor( Math.random() * 100000000)
}
The code implementation for the map is here. The main problem that I can see is that authorize step does not invoke the Dropbox authorize end point (ie no browser redirection takes place to authorize the application). If I place a breakpoint just after the line Logger.log(authStringx); and manually visit the web page pasting in the contents of authStringx I get the screen to authorize my app. I accept that and get the message that the app is registered in "My Apps". I now let the program continue and I am greeted with the message
Any ideas?
Pram,
I was trying to accomplish the same task and came across your post. I am not a programmer, so I can't figure out the second part either (launching the authorization page fails), but I was able to complete the process in the third step and connect my app successfully.
Instead of:
var authString2 = 'OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT", oauth_token="' + map.get("oauth_token") + '" , oauth_signature="' + encodeURIComponent(ScriptProperties.getProperty("dropboxSecret") + '&' + map.get("oauth_token_secret")) + '", oauth_consumer_key="' + ScriptProperties.getProperty("dropboxKey") + '",oauth_timestamp="'+ timestamp +'", oauth_nonce="' + nonce +'"';
Logger.log(authString2);
var options3 = {
"method" : "POST",
"Authorization" : authString2
}
var response3 = UrlFetchApp.fetch("https://api.dropbox.com/1/oauth/access_token", options3);
Logger.log(response3.getContentText());
I used:
var authtokenURL = "https://api.dropbox.com/1/oauth/access_token";
var authString2 = "?oauth_signature_method=PLAINTEXT&oauth_token=" + [MY_OAUTH_REQUEST_TOKEN] + "&oauth_signature=" + encodeURIComponent([MY_DROPBOX_CONSUMER_SECRET] + "&" + [MY_OAUTH_REQUEST_SECRET]) +"&oauth_consumer_key=" + [MY_DROPBOX_CONSUMER_KEY];
Logger.log(authString2);
var response3 = UrlFetchApp.fetch("https://api.dropbox.com/1/oauth/access_token" + authString2);
Logger.log(response3.getContentText());
I then got an email confirmation that I connected a new app to Dropbox, and my app does show up under Settings in my account. Anyway, as I said, I'm no programmer, so sorry for the ugly code. Thanks for supplying your code for me to make it this far. I hope this helps you at least move forward, even if it doesn't solve the underlying problem.
I am able to see this issue as well. There is something special going on here with Dropbox. You should check on their forums or with their API support team. Looks like they are not correctly accepting callback params. Perhaps this is a development mode limitation (vs. production mode). Or perhaps they are stringent about some POST vs GET differences that Google doesn't support.
This code below exhibits the same issue you described where the authorization is never complete.
function dropbox() {
var oAuthCfg = UrlFetchApp.addOAuthService("dropbox");
oAuthCfg.setAccessTokenUrl('https://api.dropbox.com/1/oauth/access_token');
oAuthCfg.setRequestTokenUrl('https://api.dropbox.com/1/oauth/request_token');
oAuthCfg.setAuthorizationUrl('https://api.dropbox.com/1/oauth/authorize');
oAuthCfg.setConsumerKey('DROPBOX_KEY');
oAuthCfg.setConsumerSecret('DROPBOX_SECRET');
var options = {oAuthServiceName:'dropbox',oAuthUseToken:'always'}
var url = 'https://api.dropbox.com/1/account/info';
var response = UrlFetchApp.fetch(url, options).getContentText();
Logger.log(response);
}
However, the same code works without issue with the Twitter OAuth 1 API. The code below should dump out JSON from your stream (once you substitute the tokens from your setup in http://dev.twitter.com
function twitter(){
var oAuthCfg = UrlFetchApp.addOAuthService('twitter');
oAuthCfg.setAccessTokenUrl('http://api.twitter.com/oauth/access_token');
oAuthCfg.setRequestTokenUrl('http://api.twitter.com/oauth/request_token');
oAuthCfg.setAuthorizationUrl('http://api.twitter.com/oauth/authorize');
oAuthCfg.setConsumerKey('TWITTER_KEY');
oAuthCfg.setConsumerSecret('TWITTER_SECRET');
var options = {oAuthServiceName:'twitter',oAuthUseToken:'always'}
var url = "http://api.twitter.com/1/statuses/user_timeline.json";
var response = UrlFetchApp.fetch(url, options).getContentText();
Logger.log(response);
}
If you are able to narrow this down to a Google issue log a bug here on the Issue Tracker.
This question already has answers here:
Google app scripts: email a spreadsheet as excel
(2 answers)
Closed 2 years ago.
I would like to write an apps script to email an excel version of my Google Spreadsheet. I know I can save the spreadsheet as an Excel file. I am not sure if I can use the script to email the excel version out as an attachment. How can this be done?
After an answer on another recent post (Thomas van Latum), I tried the suggested doc api and get an interesting result... here is the test code I used and that is working nicely except the file is in xlsx format, not in xls but this is not necessarily an issue these days :
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey('anonymous');
oAuthConfig.setConsumerSecret('anonymous');
return {oAuthServiceName:name, oAuthUseToken:"always"};
}
function test(){
var id = 'spreadsheet_ID'
var url = 'https://docs.google.com/feeds/';
var doc = UrlFetchApp.fetch(url+'download/spreadsheets/Export?key='+id+'&exportFormat=xls',
googleOAuth_('docs',url)).getBlob()
DocsList.createFile(doc).rename('newfile.xls')
}
note : if you don't rename it, its default name is Export.xlsx , it might be more usefull to get its ID to use it later...
so the last line could be like this instead :
var xlsfileID = DocsList.createFile(doc).getId()
EDIT : to trigger the authorization process, try a small function like this, run it from the script editor
function autorise(){
// function to call to authorize googleOauth
var id=SpreadsheetApp.getActiveSpreadsheet().getId();
var url = 'https://docs.google.com/feeds/';
var doc = UrlFetchApp.fetch(url+'download/documents/Export?exportFormat=html&format=html&id='+id,
googleOAuth_('docs',url)).getContentText();
}
As I spent about four hours of playing Rumpelstiltskin because none of the typically very old code snippets for the old Spreadsheet versions and the old OAUTH you can find when googling "google docs script send excel attachment" or similar (i.e. you want to take an existing Spreadsheet, convert it to Excel format and send it as email attachment) actually worked, I finally found the solution.
To create the actual attachment content, neither the supposed res.getContent() nor res.getBlob() nor res.getBytes alone worked. These hints are misleading!
The only thing that works for me is response.getBlob().getContent()!
Whole code :
function sendCurrentDocAsEmail() {
var driveService = getDriveService();
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getName();
var email = "recipient#demo.com"
var subject = "Here be Subjects";
var body = "Don't even think about learning how to code. It's wasted time.";
var file = Drive.Files.get(ssID );
var url = file.exportLinks[MimeType.MICROSOFT_EXCEL];
var response = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + driveService.getAccessToken()
}
});
var attachments = [{
fileName:sheetName+".xlsx",
content: response.getBlob().getBytes(), // this single line has cost me hours!
mimeType:"application//xls",
headers: {
Authorization: 'Bearer ' + driveService.getAccessToken()
}
}];
MailApp.sendEmail(email,subject ,body, {attachments:attachments});
}
Where getDriveService() is a function from Google's "OAuth2 for Apps Script" readme on https://github.com/googlesamples/apps-script-oauth2
The latest working version is below. Based on this example, i.e. similar as in previous answer but uses Google Service Account which does not require a human going by link to receive a token. You have to install Oath library from Google, the instructions are pretty clear.
var PRIVATE_KEY = 'xxx'
var CLIENT_EMAIL = 'xxx';
var USER_EMAIL=Session.getActiveUser().getEmail()
function getOathService() {
return OAuth2.createService('GoogleDrive:' + USER_EMAIL)
// Set the endpoint URL.
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
// Set the private key and issuer.
.setPrivateKey(PRIVATE_KEY)
.setIssuer(CLIENT_EMAIL)
// Set the name of the user to impersonate. This will only work for
// Google Apps for Work/EDU accounts whose admin has setup domain-wide
// delegation:
// https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
.setSubject(USER_EMAIL)
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getScriptProperties())
// Set the scope. This must match one of the scopes configured during the
// setup of domain-wide delegation.
.setScope('https://www.googleapis.com/auth/drive');
}
function sendEmail() {
var oathService = getOathService();
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var file = Drive.Files.get(ssID );
var url = file.exportLinks[MimeType.MICROSOFT_EXCEL];
var file = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + oathService.getAccessToken()
}
});
var attachments = [{
fileName:'xxx.xls',//TODO DATE
content: file.getBlob().getBytes(),
mimeType:"application//xls",
headers: {
Authorization: 'Bearer ' + oathService.getAccessToken()
}
}];
MailApp.sendEmail('email#domain.com', 'xxx', 'Hi,\n\nPlease see the last data in attachment',{attachments:attachments});
}
The one that worked for me:
var AUTH_TOKEN = "Enter your OAuth_Token";
ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var url = "http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key="+ ssID + "&exportFormat=xls";
//Add &gid=x at the end of above url if you only want a particular sheet
var auth = "AuthSub token=\"" + AUTH_TOKEN + "\"";
var res = UrlFetchApp.fetch(url, {headers: {Authorization: auth}});
var attachments = [{fileName:"<Filename>.xls", content: res.getContent(),mimeType:"application/vnd.ms-excel"}];
MailApp.sendEmail("<recipient's email id>", "<email subject>", "<email body>", {attachments: attachments});
Get OAuth documentation & you token from here https://developers.google.com/accounts/docs/OAuth2
Use the following snippet of code after modifying it to suit your needs
var file = DocsList.getFileById(FILE_ID);
var attachment = file.getAs('application/vnd.ms-excel');
MailApp.sendEmail("abcd#example.com", "Subject", " Body" , {"fileName": "Your_file_name" , "mimeType" : "application/vnd.ms-excel" , "content":attachment.getBytes() } );
Note that this code is not tested, so please feel free to fix an error or two that might pop up