google-apps-scriptgmailgmail-apireply

Sending a reply draft using Gmail API results in "Invalid draft" error


I'm trying to send a reply to the first (original) message of a thread using the Gmail API in Apps Script. The code successfully creates a draft with the reply content, but when attempting to send the draft using Gmail.Users.Drafts.send(), I receive an "Invalid draft" error. I should also add that I previously tried Gmail.app method and it only sends the reply to the sender of the first message (me).

Here's the relevant code snippet:


    var thread = GmailApp.getThreadById(existingThreadId); 
 var messages = thread.getMessages();
// Retrieve the original message
var originalMessage = messages[0];
var recipientEmail = originalMessage.getTo();
var senderEmail = Session.getActiveUser().getEmail();

// Create a draft reply
var draftReplyRequestBody = {
  message: {
    threadId: existingThreadId,
    raw: Utilities.base64EncodeWebSafe("Test Test Test"),
    payload: {
      headers: [
        { name: "Reply-To", value: recipientEmail } // Add the Reply-To header with the recipient email address
      ]
    }
  }
};

var draftReplyResponse = Gmail.Users.Drafts.create(draftReplyRequestBody, "me");
var draftReplyId = draftReplyResponse.id;

// Send the draft reply using Gmail API
var sendReplyParams = {
  userId: "me",
  draftId: draftReplyId
};

// Log the email body and thread ID for verification
console.log('Email Body:', draftReplyRequestBody);
console.log('Thread ID:', existingThreadId);
console.log('Draft Reply ID:', draftReplyId);

Gmail.Users.Drafts.send(sendReplyParams, "me");

I have verified that the values for recipientEmail, existingThreadId, and draftReplyRequestBody are correct by logging them. However, when executing the Gmail.Users.Drafts.send() function, I encounter the "Invalid draft" error:

"GoogleJsonResponseException: API call to gmail.users.drafts.send failed with error: Invalid draft"

I have also checked the documentation and made sure that the required properties are set, such as the threadId and raw content encoded in base64 web-safe format.

Could someone please help me identify what could be causing this "Invalid draft" error and provide guidance on how to resolve it?

Thank you in advance for your assistance!


Solution

  • Modification points:

    When these points are reflected in your script, how about the following modification?

    Modified script:

    var thread = GmailApp.getThreadById(existingThreadId);
    var messages = thread.getMessages();
    var originalMessage = messages[0];
    var recipientEmail = originalMessage.getTo();
    var senderEmail = Session.getActiveUser().getEmail();
    var messageId = originalMessage.getHeader("Message-ID");
    var data = [
      "MIME-Version: 1.0\n",
      `In-Reply-To: ${messageId}\n`,
      `Subject: Re:${originalMessage.getSubject()}\n`,
      `From: ${senderEmail}\n`,
      `To: ${recipientEmail}\n\n`,
      "Test Test Test",
    ].join("");
    var draftReplyRequestBody = {
      message: {
        threadId: existingThreadId,
        raw: Utilities.base64EncodeWebSafe(data),
      }
    };
    var draftReplyResponse = Gmail.Users.Drafts.create(draftReplyRequestBody, "me");
    var draftReplyId = draftReplyResponse.id;
    var sendReplyParams = { id: draftReplyId };
    console.log('Email Body:', draftReplyRequestBody);
    console.log('Thread ID:', existingThreadId);
    console.log('Draft Reply ID:', draftReplyId);
    Gmail.Users.Drafts.send(sendReplyParams, "me");
    

    References: