I have set up a Gsheet in which there are several Email for which drafts need to be created. I use the following code to achieve this:
const RECIPIENT_COL = "Recipient";
const CC= "Sidekick email address";
const DRAFT_CREATED_COL = "Draft created";
const SUBJECT_COL="Subject";
const TEXT="Text";
/**
* Creates the menu item "Mail Merge" for user to run scripts on drop-down.
*/
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu('Create Drafts')
.addItem('Create Drafts', 'createDraft')
.addToUi();
}
function createDraft(sheet=SpreadsheetApp.getActiveSheet()) {
const dataRange = sheet.getDataRange();
// Fetch displayed values for each row in the Range HT Andrew Roberts
// https://mashe.hawksey.info/2020/04/a-bulk-email-mail-merge-with-gmail-and-google-sheets-solution-evolution-using-v8/#comment-187490
// @see https://developers.google.com/apps-script/reference/spreadsheet/range#getdisplayvalues
const data = dataRange.getDisplayValues();
// assuming row 1 contains our column headings
const heads = data.shift();
// get the index of column named 'Email Status' (Assume header names are unique)
// @see http://ramblings.mcpher.com/Home/excelquirks/gooscript/arrayfunctions
const emailSentColIdx = heads.indexOf(DRAFT_CREATED_COL);
// convert 2d array into object array
// @see https://stackoverflow.com/a/22917499/1027723
// for pretty version see https://mashe.hawksey.info/?p=17869/#comment-184945
const obj = data.map(r => (heads.reduce((o, k, i) => (o[k] = r[i] || '', o), {})));
// used to record sent emails
const out = [];
// loop through all the rows of data
obj.forEach(function(row, rowIdx){
// only send emails is email_sent cell is blank and not hidden by filter
if (row[DRAFT_CREATED_COL] == ''){
try {
// @see https://developers.google.com/apps-script/reference/gmail/gmail-app#sendEmail(String,String,String,Object)
GmailApp.createDraft(row[RECIPIENT_COL], row[SUBJECT_COL], row[TEXT], {
//htmlBody: emailHtml,
cc: row[CC],
});
// modify cell to record email draft created date
out.push([new Date()]);
} catch(e) {
// modify cell to record error
out.push([e.message]);
}
} else {
out.push([row[DRAFT_CREATED_COL]]);
}
});
// updating the sheet with new data
sheet.getRange(2, emailSentColIdx+1, out.length).setValues(out);
}
However, this does not include the links you can find in the GSheet I use, which you can find here: https://docs.google.com/spreadsheets/d/1hCcEr7L3ejGZJihJ5TPxwX8XMHd0jomHK22zhA5-0y8/edit?usp=sharing
I thought about changing the respective section to the following code section:
emailText=msg.getPlainBody();
emailHtml=msg.getBody();
GmailApp.createDraft(row[RECIPIENT_COL], row[SUBJECT_COL], emailText, {
htmlBody: emailHtml,
Note that this throws the error msg.getPlainBody is not a function
. How could I fix this or how could I include the links (maybe with correct html formatting)?