Search code examples
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:

    • In your script, I thought of the following modification.
      • In this case, please use raw of the web-safe base64 encoded data including "From", "To", "Subject", "Body".
      • The request body of sendReplyParams is not correct. I thought that the reason for your current issue of GoogleJsonResponseException: API call to gmail.users.drafts.send failed with error: Invalid draft might be due to this.

    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");
    
    • When this script is run, an email is replied to existingThreadId by preparing a draft.

    • In this modification, it supposes that the values of senderEmail, recipientEmail are valid values. Please be careful about this.

    • From your following reply,

      I tried this , although I changed the "getFrom();" in line for to "getTo();" because I wanna send a reply to a message which has been sent by me to other one. It worked fine but there is a problem. Recipient received that reply as a separate email and not appended to the thread as a reply. ( the recipient is using gmail too). how to modify the code in order to quote the original message of the thread and send a reply as gmail UI?

      • I updated the above script.

    References: