I'm using the Gmail API in Google Apps Script to send a reply to the first (original) message of a thread. The code works fine and sends the reply in the same thread for both the sender and recipients using Gmail. However, when the recipient's email service is not Gmail and doesn't provide threading or conversation grouping, the recipient receives the follow-up email (reply) as a separate email without the body of the original message. In other words, the reply doesn't quote the original message.
Here's a snippet of the code I'm currently using:
var thread = GmailApp.getThreadById(existingThreadId);
var messages = thread.getMessages();
if (messages.length > 0) {
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`,
"This is a reminder for previous email",
].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 };
Gmail.Users.Drafts.send(sendReplyParams, "me");
}
Is there a way to modify this code to include the quoting of the original message in the reply, similar to how Gmail UI quotes the original message in a reply? I want the recipient to see the original message and its attachments within the reply. This way, Gmail users will receive the reply in the same thread with a quote of the main email, while non-Gmail users may receive it as a separate email but with the original email quote.
Any insights or suggestions would be greatly appreciated. Thank you in advance!
From your following reply,
No there is no need to include all of the thread messages. Only include the message we send a reply on it. Suppose there are messages A, B, C, D,... in the thread, we decide to reply to the message of C, so I want to only include the message C (as a quotation) in the reply email.
In this case, how about the following modification?
var data = [
"MIME-Version: 1.0\n",
`In-Reply-To: ${messageId}\n`,
`Subject: Re:${originalMessage.getSubject()}\n`,
`From: ${senderEmail}\n`,
`To: ${recipientEmail}\n\n`,
"This is a reminder for previous email",
].join("");
var emailBody = "This is a reminder for previous email\n\n" + messages.pop().getPlainBody().replace(/^/gm, "> ");
var data = [
"MIME-Version: 1.0\n",
`In-Reply-To: ${messageId}\n`,
`Subject: Re:${originalMessage.getSubject()}\n`,
`From: ${senderEmail}\n`,
`To: ${recipientEmail}\n\n`,
emailBody,
].join("");