I’m trying to trigger a Google Apps Script to copy an attached xlsx file from a Gmail email to a Google Sheet, but I’m getting the following error:
GoogleJsonResponseException: API call to drive.files.insert failed with error: Bad Request
fetch @ fetch.gs:17
Line 17 in my code is:
var convertedSpreadsheetId = Drive.Files.insert({ mimeType: MimeType.GOOGLE_SHEETS }, xlsxBlob).id;
And this is the full code before line 17:
function fetch() {
var searchQuery = "in:inbox from:[email protected] has:attachment filename:Stockfile filename:.xlsx";
var threads = GmailApp.search(searchQuery);
if (threads.length > 0) {
var latestThread = threads[0];
var latestEmail = latestThread.getMessages()[0];
var attachments = latestEmail.getAttachments();
if (attachments.length > 0) {
for (var i = 0; i < attachments.length; i++) {
var attachment = attachments[i];
var attachmentName = attachment.getName();
if (attachmentName.indexOf("stockfile") === 0) {
var xlsxBlob = attachment;
var convertedSpreadsheetId = Drive.Files.insert({ mimeType: MimeType.GOOGLE_SHEETS }, xlsxBlob).id;
var sheet = SpreadsheetApp.openById(convertedSpreadsheetId).getSheets()[0];
var data = sheet.getDataRange().getValues();
I’m not exactly sure what the issue is, but I should point out that this code was working for months in 2022. I’ve only just gotten back to it and for some reasons I can’t get it to work. I’m not sure what changed, in the code and/or in Google Apps Scripts.
The Drive services is set to v2, I’ve tried changing it to v3 but then Drive.Files.insert
is not a function in v3.
Didi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.