-
Notifications
You must be signed in to change notification settings - Fork 0
/
Code.js
58 lines (50 loc) · 1.91 KB
/
Code.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//ideas from: https://spreadsheet.dev/send-html-email-from-google-sheets
// This constant value is written to column C in rows for which an email
// has been successfully sent.
const EMAIL_SENT = 'EMAIL_SENT';
/**
* Sends non-duplicate emails with data from the current spreadsheet.
*/
function sendEmails(){
let sheet = SpreadsheetApp.getActiveSheet();
let startRow = 2; // First row of data to process
let startCol = 1;
let numRows = 290; // Number of rows to process
let numCols = 4;
const emailSentColumn = 5;
let dataRange = sheet.getDataRange(); //use sheet.getRange(startRow, startCol, numRows, numCols) to retrieve specific range of rows/columns;
// Fetch values for each row in the Range.
let data = dataRange.getValues();
data.shift(); //remove headers
data.forEach(function(row, index) {
let emailAddress = row[1]; // First column
let link = row[3];
let htmlMessage = getEmailHtml(link);
let txtMessage = getEmailText(link);
let emailSent = row[4]; // 4th column
let subject = 'My dummy subject';
if(emailAddress && (emailSent !== EMAIL_SENT)){ // Prevents sending duplicates
MailApp.sendEmail({
to: emailAddress,
subject: subject,
body: txtMessage,
htmlBody: htmlMessage
});
sheet.getRange(startRow + index, emailSentColumn).setValue(EMAIL_SENT); //mark the sent row with email sent
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
});
}
function getEmailHtml(data){
let htmlTemplate = HtmlService.createTemplateFromFile("Template.html");
htmlTemplate.data = data;
let htmlBody = htmlTemplate.evaluate().getContent();
return htmlBody;
}
function getEmailText(data){
let htmlTemplate = HtmlService.createTemplateFromFile("Template.txt.html");
htmlTemplate.data = data;
let htmlBody = htmlTemplate.evaluate().getContent();
return htmlBody;
}