I’m working on a Google Apps Script project connected to a spreadsheet and I need to modify an existing Gmail draft. My code works fine when I test it in the browser but fails in the script editor.
function modifyDraft(){
var encodedMessage = Utilities.base64Encode('From:[email protected]\nTo:[email protected]\nSubject:Updated subject\n\nNew message content');
var response = Gmail.Users.Drafts.update({
'id': '1234567890987654321',
'message': {'raw': encodedMessage},
'send': false
}, 'me');
console.log(response);
}
This throws an error about wrong number of arguments. The browser version works but uses a different approach:
What’s the correct way to call the Gmail API draft update method in Google Apps Script? I’ve tried many different parameter combinations but keep getting the same argument count error.
Yeah, this tripped me up too when I started using Gmail API with Apps Script. The problem is Apps Script’s advanced services want positional parameters, not everything bundled in one object like you’d expect. So Gmail.Users.Drafts.update needs the draft ID first, then user ID, then the request body as separate parameters. Your browser code works fine because gapi.client follows normal REST conventions. Also check that your draft ID is still valid - drafts can expire or get modified by other stuff running. I’ve seen cases where the draft got deleted between grabbing the ID and trying to update it.
you’ve got the parameters in the wrong order. apps script wants draftId first, then userId, then the request body. try Gmail.Users.Drafts.update('1234567890987654321', 'me', {'message': {'raw': encodedMessage}}) instead. also check that gmail api is enabled in resources > advanced google services.
Your parameter structure is wrong. In Google Apps Script, you need to pass draftId and userId as separate arguments, not wrapped in an object like you’d do in the browser.
Here’s the fix:
function modifyDraft(){
var encodedMessage = Utilities.base64Encode('From:[email protected]\nTo:[email protected]\nSubject:Updated subject\n\nNew message content');
var response = Gmail.Users.Drafts.update(
'1234567890987654321', // draftId
'me', // userId
{
'message': {'raw': encodedMessage}
}
);
console.log(response);
}
I ran into the same thing when switching from browser Gmail API to Apps Script. The advanced services use a different calling method than the JavaScript client library. Also, make sure you’ve enabled the Gmail API in your script’s advanced Google services settings.