apps script : xls attach in gmail to google spreadsheet - google-apps-script

I try open a xls with app script.
I can get the content type of file with:
var attach = messages[j].getAttachments()[0];
var name = attach.getName();
var type = attach.getContentType();
And I get:
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
but, How I can read the information in the cells ?
 EDIT
If I use
DocsList.createFile(attach);
the attach is added in google Docs list.

I solved uploaded the file with drive
https://gist.github.com/4666836

Related

Apps Script - Search Gmail label for all attachments and overwrite files to google drive folder

Using prior articles and questions found within stack overflow I was able to find a snippet of App Script that searches Gmail labels for attachments and moves them to a specific folder in Google Drive.
function saveAttachmentInFolder(){
var folder = DriveApp.getFolderById('xxosi2');
var userId = "please.thanks#gmail.com";
var query = "label:thankyoucards-reports";
var res = Gmail.Users.Messages.list(userId, {q: query});//I assumed that this works
res.messages.forEach(function(m){
var attA=GmailApp.getMessageById(m.id).getAttachments();
attA.forEach(function(a){
folder.createFile(a.copyBlob()).setName(a.getName());
});
});
}
I need to modify this code to perform the following additional functions:
If file exists, overwrite and retain version history
I have also played around with the answer found in the following thread to no avail as I believe this is hard coded in some way and too specific to the one file type (xlsx) Copying attachments from Gmail to Google Drive folder and overwriting old files with Apps Script.
I believe your goal is as follows.
You want to check this using the filename between the existing file in the folder and the attachment file.
You want to overwrite the existing file with the attachment file.
In this case, how about the following modification? In this case, Drive API is used. So, please enable Drive API at Advanced Google services.
From:
folder.createFile(a.copyBlob()).setName(a.getName());
To:
var filename = a.getName();
var files = folder.getFilesByName(filename);
if (files.hasNext()) {
Drive.Files.update({}, files.next().getId(), a.copyBlob(), {supportsAllDrives: true});
} else {
folder.createFile(a.copyBlob()).setName(filename);
}
When this modified script is run, the existing file is searched from the folder using the filename of the attachment file. When the file is found, the file is overwritten by the attachment file. When the file is not found, the file is created as a new file.
Note:
In this modified script, the existing file is overwritten. So, please be careful about this. I would like to recommend using a sample file for testing the script.
Reference:
Files: update of Drive API v2

Attach a Google Docs file in an email with Google App Scripts

I'm trying to attach a Google Docs file to an email using Google App Scripts.
I have a folder with the file inside and the idea is to get the file from there and send it by email using also an email address that is saved in a google sheet.
I founded and used this:
function emailDocTestasDocx() {
var id = '1egjazIip6zuPneKh2sVFTvbK06asd4ZgAvrgjw';// an example of Google doc
var url = 'https://docs.google.com/document/d/1egjaasdasdeKh2sVFTvbK06z4JbPqnm4ZgAvrgjw';
var doc = UrlFetchApp.fetch(url);
var me = Session.getEffectiveUser().getEmail();
MailApp.sendEmail(me, 'test', 'see attachment', {attachments:[doc]});
}
It works but the final attachment is an html that redirects me to the doc inside the folder. I don't want that. I want to send the attachment but I didn't found a way to to this yet.
Any ideas? Thanks!
As what #Karan have mentioned on the comments, Google Docs are not something you can open outside of the cloud (it is always being opened via docs.google.com website via a link) so you cannot attach them as a file on the mail. You can either attach the document as PDF or export the Docs file first as a document with .docx extension & then save the file on your Google Drive:
Sample tweaked script that will send attach the Google doc file as PDF:
function emailDocTestasDocx() {
var id = '1egjazIip6zuPneKh2sVFTvbK06asd4ZgAvrgjw';// an example of Google doc
var url = 'https://docs.google.com/document/d/1egjaasdasdeKh2sVFTvbK06z4JbPqnm4ZgAvrgjw';
var doc = DriveApp.getFileById(id); //used ID to get the file saved in your Drive using DriveApp.getFileById() method
var me = Session.getEffectiveUser().getEmail();
MailApp.sendEmail(me, 'test', 'see attachment', {attachments:[doc]}); //attach the file via email
}
Sample Result
You may also check the answers from these similar posts:
Convert Google Doc to PDF using Google Script Editior
Google Apps Script: Send docx email attachment
Send email with an attachment located in Google Drive

How to get XML File parsed from Google Drive without sharing the Link globaly

I'm building a XML parser in Google App Script, witch gets XMLs from Google Drive. At the moment i could only get it to work, when the link of the XML file is shared global.
function XmlChecker(FileID){
var data = UrlFetchApp.fetch("https://drive.google.com/uc?id=" + FileID + "&export=download").getContentText();
var xml = XmlService.parse(data);
var root = xml.getRootElement();
var namespace = XmlService.getNamespace('http://www.editeur.org/onix/2.1/short');
Is there a way to get the same result without sharing the link?
The Google App Scripts is build in a Spreadsheet. Can i give the spreadsheet access via code?
If the file of FileID is in your Google Drive, how about retrieving the data using Drive service as follows?
From:
var data = UrlFetchApp.fetch("https://drive.google.com/uc?id=" + FileID + "&export=download").getContentText();
To:
var data = DriveApp.getFileById(FileID).getBlob().getDataAsString();
By this modification, the data can be retrieved from the file of FileID without publicly sharing.
Reference:
Drive Service

Convert Google Sheets to .xls

Would anyone have any pointers as to how to convert a Google sheets file to a .xls file through Google App Script?
Many thanks
Here's what I theorized, but the logic is flawed. I've also attempted the Blobs approach as well and it seems most files are defaulted to application/pdf.
function gs2xls() {
var gSheets = DocsList.getFilesByType('spreadsheet');
for(var i = 0; i < gSheets.length; i++){
var gSheetFile = gSheets[i]; //File
var gSheetSS = SpreadsheetApp.open(gSheetFile); //Spreadsheet of gs file
var gSheet = gSheetSS.getActiveSheet();
var xlsSS = SpreadsheetApp.create(gSheetFile.getName() + ".xls");
xlsSS.setActiveSheet(gSheet);
}
}
Google Apps Script can't export anything else than pdf natively but the document API does so you can use urlFetch with parameters to get what you want.
The code is shown with explanations in this post : Google apps script to email google spreadsheet excel version
It works pretty well.
That approach will never work because:
1) You are creating and empty google spreadsheet, not a file of type xls.
2) you are setting as active sheet an invalid sheet (from another spreadsheet whivh is not what setactivesheet does).
The most you will be able to achieve is to show the user an export link that downloads the file as xls. Google how to make the export link.

Script to unzip attachment

I was trying to create a Google Apps Script, that takes attachment of e-mails, unzips it a forwards it. I saw unpacking feature in Google Drive (you can upload a file there, open it and copy individual files to you drive). Is this functionality accessible from Google Apps Script somehow?
First you need to write a script for automatically makes attachments of an email as directly uploaded on user's Google Drive after this trigger run this piece of code shown below
function testzip(){
var files=DocsList.getRootFolder().find('Sans titre.txt.zip');
var zipblob=files[0].getBlob();
var unzipblob = Utilities.unzip(zipblob);
var unzipstr=unzipblob[0].getDataAsString();// it is a text file
DocsList.createFile('Sans titre.txt',unzipstr);// I kept the original name to make it simple
}
Check this code. Don't blame me if it won't work. It's just a proposal.
Comment: Files are blobs so need to call getBlob(). Anything that has a getBlob() function can be used as a blob directly. You can replace
var zipblob=files[0].getBlob();
var unzipblob = Utilities.unzip(zipblob);
with this:
var zipfile=files[0];
var unzipblob = Utilities.unzip(zipfile);
I tried to edit the other answer, but someone who apparently didn't try the code rejected the edit as incorrect.