Modifying Gmail draft using Apps Script and Gmail API

I’m working on a Google Apps Script project linked to a spreadsheet. I want to change a draft email using the Gmail API. Here’s what I’ve tried:

function updateDraftMessage() {
  var encodedEmail = Base64.encode('From:[email protected]\nTo:[email protected]\nSubject:Updated Draft\n\nNew content');
  var draftUpdate = Gmail.Users.Drafts.update({
    'id': 'draft123456',
    'message': {'raw': encodedEmail},
    'send': false
  }, 'me');
  
  Logger.log(draftUpdate);
}

But I’m getting an error about wrong number of arguments. I know it works in the browser with gapi.client.gmail.users.drafts.update(), but I need it to work in Apps Script. I’ve looked at the API docs and tried different ways to call the function, but nothing seems to work. Any suggestions on how to fix this in Apps Script?

hey samuel87, i’ve run into this before. try using the GmailApp class instead of the API directly. it’s way easier:

function updateDraft() {
var draft = GmailApp.getDraftMessages()[0];
draft.update(‘New Subject’, ‘New Body’);
Logger.log(‘draft updated’);
}

this should work without any weird encoding stuff. lmk if u need more help!

I’ve dealt with similar issues when working with the Gmail API in Apps Script. The problem is likely due to how Apps Script handles the Gmail.Users.Drafts.update() method differently from the browser version.

Here’s what worked for me:

function updateDraftMessage() {
  var draft = GmailApp.getDraftMessages()[0]; // Get the first draft, adjust as needed
  var draftId = draft.getId();
  
  var newBody = 'New content';
  var newSubject = 'Updated Draft';
  
  draft.update(newSubject, newBody);
  
  Logger.log('Draft updated successfully');
}

This approach uses GmailApp instead of the Gmail API directly. It’s simpler and avoids encoding issues. Just make sure you have the necessary scopes enabled in your Apps Script project.

If you need more control or specific API features, you might need to use UrlFetchApp to make direct REST API calls, but that’s more complex. Let me know if you need help with that approach.

I’ve encountered this issue before when working with the Gmail API in Apps Script. The problem stems from the differences between the browser and Apps Script environments. Here’s a solution that should work:

function updateDraftMessage() {
var draftId = ‘draft123456’;
var draft = GmailApp.getDraft(draftId);

var newSubject = ‘Updated Draft’;
var newBody = ‘New content’;

draft.update(newSubject, newBody);

Logger.log(‘Draft updated successfully’);
}

This method uses GmailApp, which is more reliable in Apps Script. Make sure you have the correct scopes enabled in your project settings. If you need more advanced features, consider using UrlFetchApp to make direct API calls, though that requires more setup. Let me know if you need further assistance.