I built a Google Apps Script that automates email replies but I’m having trouble keeping the replies in the same conversation thread. When I send the replies, they show up as separate emails instead of being grouped together with the original message.
The script should copy recipients from the original email, add custom text, and save everything as a draft. Here’s what I have so far:
function buildReplyInterface() {
var divider = CardService.newDivider();
var messageInput = CardService.newTextInput()
.setFieldName("replyText")
.setMultiline(true);
var submitAction = CardService.newAction()
.setFunctionName('generateDraftReply');
var submitBtn = CardService.newTextButton()
.setText('Create Draft')
.setComposeAction(submitAction, CardService.ComposedEmailType.REPLY_AS_DRAFT);
var section = CardService.newCardSection()
.addWidget(messageInput)
.addWidget(divider)
.addWidget(submitBtn);
return CardService.newCardBuilder()
.addSection(section)
.build();
}
function generateDraftReply(e) {
var msgId = e.gmail.messageId;
var originalMsg = GmailApp.getMessageById(msgId);
var recipients = originalMsg.getTo();
var sender = originalMsg.getFrom();
var ccList = originalMsg.getCc();
var emailSubject = originalMsg.getSubject();
var originalContent = originalMsg.getBody();
var files = originalMsg.getAttachments();
var requiredEmail = "[email protected]";
var needsEmail = ccList.indexOf(requiredEmail) < 0;
if (needsEmail) {
ccList += ", " + requiredEmail;
}
var userText = e.formInputs.replyText;
var newContent = "<br>" + userText + "<br><br>" + originalContent;
var draftReply = originalMsg.createDraftReply('', {
cc: ccList,
htmlBody: newContent,
attachments: files,
replyTo: sender,
subject: emailSubject
});
return CardService.newComposeActionResponseBuilder()
.setGmailDraft(draftReply)
.build();
}
What am I missing to make sure the draft stays in the same conversation thread when sent?