DriveApp createFile from GmailApp attachment not working - google-apps-script

First time posting, so please be gentle.
I'm using bits of code from:
https://www.splitbrain.org/blog/2017-01/30-save_gmail_attachments_to_google_drive
https://ctrlq.org/code/19053-send-to-google-drive
I'm trying to save PDF attachments from Gmail directly to Google drive. I'm getting an Invalid Argument error when trying to save the file in the last line of code below.
I have a loop to go through message threads and then within that loop, this is the code that is saving the attachments:
var message = threads[x].getMessages()[0];
var saveFolder = getFolder(driveFolderID,message);//this is valid folder
var att = message.getAttachments();
Logger.log(att[0].getContentType()); //this returns 'pdf'
file = saveFolder.createFile(att[0]);
Anyone know what I'm doing wrong, or where to look next?
Thanks

Ok. So I managed to figure this out so just updating.
Apparently the contentType 'pdf' was causing the problem. If I do a att[0].setContentType('application/pdf') before trying to save the file, then the code works as expected.

Related

Importing .csv content from gmail into gsheet - script works - content shows strange symbols

when running my script to import .csv content from gmail it works and runs fine without any errors. But the content within the sheet is off. Strange thing is same script for other files works without problems - so I am wondering what is causing it. I checked the .csv and it is actually separated by semi colons (;) and structure wise it is exactly same as other .csvs where the script works fine. So I am really puzzled as why its not working, and it is every file from this person that I get daily that this doesnt work with.
var threads = GmailApp.search('from:xyz#gmail.com subject:xyz');
var messages = threads[0].getMessages();
var file = messages[0].getAttachments()[0];
var contents = Utilities.parseCsv(file.getDataAsString(), ";");
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh0 = ss.getSheetByName("Test");
sh0.clearContents();
sh0.getRange(1, 1, contents.length, contents[0].length).setValues(contents);
This is what it looks like after the script ran successfully
Similar thing with another file in another sheet
Any help would be highly appreciated!
Kind regards
EDIT*:
Used belows formula. Unfortunately this only reduced the amount of symbols in the sheet.
(Compare it to above pictures)
If I increase the slicer to be more than the symbols I get following error:
TypeError: Cannot read property 'length' of undefined
*EDIT2:
Console log shows the same symbol as in screenshot. Here is the file: https://file.io/uh9thiY0ZKko
First as above
Removed onyl few symbols

I get an error message when trying to retrieve a Drive folder in my Apps script

I get this error when trying to retrieve a folder:
Exception: Invalid argument: fields
This was working fine for a while and all the sudden it broke. Any advice?
The code is simply:
var folderID = "Abcdefgh";
var parent = DriveApp.getFolderById(folderID);
var files = parent.searchFiles("test");
I was able to fix this. The issue was in the next line. It should be
var files = parent.searchFiles("title contains 'test' ");
Now I am not sure why it was working before, but I guess it doesn't matter much. Thanks for responding.

my script "GET URL from google document" does not work any more - server failure WHY?

In general I want to print the URL of the google document I am actually working with in a text field.
If I copy the google sheet the function should also work for the new document.
I scripted a solution which was working for 20 month and now I have a problem.
Now I would like to know what could happen? Why do I have a server problem? Is is it possible to have to many google documents, (i have ~9000 - it works as a small ERP system) that the server got problems?
Formula in Google sheet:
=hyperlink(getSheetUrl()
Code in Script editor:
function getSheetUrl() {
var SS = SpreadsheetApp.getActiveSpreadsheet();
var ss = SS.getActiveSheet();
var url = '';
url += SS.getUrl();
url += '#gid=';
url += ss.getSheetId();
return url;
}
This is the error message in my document:
Error: Server error occurred. Please try saving the project again. (Row 0).
If I try to save the project in my script editor I get no failure.
If I try to run the project in my script editor I get:
A server error has occurred. Please try to save the project again.
Thanks for your answers.
Today I started the system and everything works fine.
Yesterday i was also able to run my code in a new enviroment, but i was not able to copy a existing document. there i got the failure.
Maybe it was really because the lan connection was to weak.
My company is a very rural area ;)
I will take an eye on that,
By the way.
Does anyone has another idea how to get the link from a document and print it in a textfield in the same document (hopefully you know what i mean)

Inserting Image into Google Sheets from Google Drive using Apps Script

I have been trying for 9 days to add an image that is uploaded to my drive (via the use of a google form) into my Google sheet using Apps Script, but it isn't working and I have no idea why, this is my code below:
function getImage(){
var folderImage = DriveApp.getFolderById("0B7gxdApLS0TYfm1pRHpHSG4yTm96bm1PbTZQc1VmdGpxajY4N1J4M1gtR1BiZ0lOSl9NMjQ");
Logger.log(folderImage.getFiles().next().setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.VIEW));
Logger.log(folderImage.getFiles().next().getSharingAccess());
Logger.log(folderImage.getFiles().next().getSharingPermission());
var imageFile = folderImage.getFiles().next().getBlob();
detailSheet.insertImage(imageFile, 1, 13);
}
I have even tried making the sharing and access permissions of the to be as open as possible but I keep getting this error message:
"We're sorry, a server error occurred. Please wait a bit and try again"
I find the error message ambiguous which leads me at a dead end. Usually the message gives me a good idea of where I have gone wrong.
I believe my code is correct, and during my research I have found no definitive reason this shouldn't work. Does anybody know where I am going wrong?
A solution would be great but preferably a critique on my code so I can learn :)
Couple of issues with your script:
You never bind to a specific file, so to work with the same file you have to reinitialize the iterator each time.
You don't verify its mimetype prior to using it as an image
An example that resolves those issues:
function addFolderPNGs_(sheet, folderId) {
const folder = folderId ? DriveApp.getFolderById(folderId) : DriveApp.getRootFolder(); // scope only to the root or given folder.
const imgs = folder.getFilesByType(MimeType.PNG);
var targetRow = sheet.getLastRow();
while (imgs.hasNext()) {
var img = imgs.next();
Logger.log(img.getName())
sheet.insertImage(img.getBlob(), 1, ++targetRow);
}
}
References
getFilesByType is either folder-specific (above) or operates on all of Google Drive
DriveApp
Folder
MimeTypes
Sheet#insertImage

Open a file from Google Sheets script

I've had a Google Sheets script running for some time (a year) that needs to read an HTML file from it's Google Drive directory. The code to open the file looks like this:
var myHtmlFile = UrlFetchApp.fetch("https://googledrive.com/host/0B1m........JtZzQ/myfile.htm");
... and I could use the HTM file for further parsing.
Suddenly, the code above is throwing an error 404.
Has anything changed recently, stopping me from opening the file?
After a discussion with 'azawaza' (thanks for all the tips), I have finally solved this, so I'm posting the resolution in case others fall into this.
It looks like the construct
https://googledrive.com/host/{public_folder_id}/myfile.htm
in UrlFetchApp.fetch(url, true) can no longer be used. It gives error 404.
I was getting it from the following construct (for simplicity, assuming there is only one parent folder of my spreadsheet):
...
var myId = DocsList.getFileById(SpreadsheetApp.getActive().getId());
var folderId = myId.getParents()[0].getId();
var url = "https://googledrive.com/host/" + folderId + "/myfile.htm";
// url looks like: https://googledrive.com/host/0B1m....JtZzQ/myfile.htm"
var httpResp = UrlFetchApp.fetch(url,true); //throws 404 !!!
// now, parse 'httpResp'
The solution that worked for me, is to find the file directly using this construct (again, assuming there is only one file of given name) :
var htmlCont = DocsList.find("myfile.htm")[0].getContentAsString();
// now, parse htmlCont
I don't know why the 'old' solution no longer works. As I mentioned it worked for a year.
UPDATE (May 2015)
The 'DocsList' has been deprecated, a new construct:
var files = DriveApp.getFilesByName(myURL);
if (files.hasNext()) {
var htmlCont = files.next().getBlob().getDataAsString()
}
has to be used instead
I find it strange that it ever worked before! If it did, it was probably a bug - pretty sure it was never intended to work like that with "local" files... I have never seen it mentioned anywhere that UrlFetchApp.fetch() can fetch "local" files like that.
A simple fix would be to just use proper full url of the file:
var myHtmlFile = UrlFetchApp.fetch("https://googledrive.com/host/{public_folder_id}/myfile.htm");
That will ensure your code complies with the API and does not break next time Google changes something.