-
Notifications
You must be signed in to change notification settings - Fork 22
/
mailmerge.gs
96 lines (73 loc) · 2.35 KB
/
mailmerge.gs
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
function onOpen () {
var ui = SpreadsheetApp.getUi()
ui.createMenu('Gmail Mail Merge')
.addItem('Start mail merge utility', 'main')
.addToUi()
}
function getColumnHeadings (sheet) {
var headerRange = sheet.getRange(1, 1, 1, sheet.getMaxColumns())
var rawHeader = headerRange.getValues()
var header = rawHeader[0]
var columns = {}
for (var i in header) {
if (header[i].trim() !== '') columns[header[i]] = i
}
return columns
}
function getLatestDraft () {
var drafts = GmailApp.getDraftMessages()
if (drafts.length === 0) return null
else return drafts[0]
}
function main () {
var quota = MailApp.getRemainingDailyQuota()
var ui = SpreadsheetApp.getUi()
ui.alert('Your remaining daily email quota: ' + quota)
if (quota === 0) {
ui.alert('You can not send more emails')
return
}
var labelRegex = /{{[\w\s\d]+}}/g
var sheet = SpreadsheetApp.getActiveSheet()
var draft = getLatestDraft()
if (draft === null) {
ui.alert('No email draft found in your Google account. First draft an email.')
return
}
var subject = draft.getSubject()
var htmlBodyRaw = draft.getBody()
var plainBodyRaw = draft.getPlainBody()
var emailPlaceHolder = draft.getTo()
var response = ui.alert('Do you want to send drafted message titled "' + subject + '" to ' + (sheet.getLastRow() - 1) + ' people?', ui.ButtonSet.YES_NO)
if (response === ui.Button.NO) {
ui.alert('Stopped')
return
}
var count = 0
var emailMap = {}
var columns = getColumnHeadings(sheet)
var dataRange = sheet.getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn())
var data = dataRange.getValues()
for (var i in data) {
var row = data[i]
var email = row[columns[emailPlaceHolder]]
email = email.trim()
if (email !== '' && !emailMap[email]) {
var htmlBody = htmlBodyRaw.replace(labelRegex, function (k) {
var label = k.substring(2, k.length - 2)
Logger.log('Replaced ' + k + ' with ' + row[columns[label]])
return row[columns[label]]
})
var plainBody = plainBodyRaw.replace(labelRegex, function (k) {
var label = k.substring(2, k.length - 2)
return row[columns[label]]
})
MailApp.sendEmail(email, subject, plainBody, {
htmlBody: htmlBody
})
emailMap[email] = true
count++
}
}
ui.alert(count + ' emails sent.')
}