aboutsummaryrefslogtreecommitdiff
path: root/emailing/send.js
diff options
context:
space:
mode:
Diffstat (limited to 'emailing/send.js')
-rw-r--r--emailing/send.js67
1 files changed, 67 insertions, 0 deletions
diff --git a/emailing/send.js b/emailing/send.js
new file mode 100644
index 0000000..2188afd
--- /dev/null
+++ b/emailing/send.js
@@ -0,0 +1,67 @@
1const fs = require('fs');
2// const path = require('path');
3const axios = require('axios');
4const dayjs = require('dayjs');
5const weekOfYear = require('dayjs/plugin/weekOfYear');
6const handlebars = require('handlebars');
7
8dayjs.extend(weekOfYear);
9
10(async function () {
11
12 const campaignId = 'b03de6fc-ff95-40a0-8707-c0706b3c0b31';
13 const from = { name: 'Mitja Felicijan', email: 'weekly@mitjafelicijan.com' };
14
15 const headers = {
16 'Authorization': 'Bearer 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',
17 'Content-Type': 'application/json',
18 };
19
20 // gets current week
21 let campaign = null;
22 try {
23 campaign = require(`./campaigns/${dayjs().format('YYYY')}-${dayjs().week()}.json`);
24 } catch (err) {
25 console.error(err);
26 process.exit(1);
27 }
28
29 // gets list subscribers
30 const personalizations = [];
31 const contacts = await axios.get('https://api.sendgrid.com/v3/marketing/contacts', { headers: headers }).catch(error => { console.log(error) });
32 if (contacts) {
33 for (const contact of contacts.data.result) {
34 if (contact.list_ids.includes(campaignId)) {
35 personalizations.push({ to: [{ email: contact.email }] });
36 }
37 }
38 }
39
40 // gets handlebars template contents
41 let template = null;
42 try {
43 template = handlebars.compile(fs.readFileSync('template.hbs', 'utf8'));
44 template = template(campaign);
45 } catch (e) {
46 console.error(err);
47 process.exit(1);
48 }
49
50 // send actual emails
51 await axios.post('https://api.sendgrid.com/v3/mail/send', {
52 from,
53 subject: `Week #${dayjs().week()} Links`,
54 personalizations,
55 content: [{
56 type: 'text/html',
57 value: template
58 }]
59 }, { headers: headers }).catch(error => { console.log(error) });
60
61 // report
62 console.log(`Emailing sent to ${personalizations.length} subscribers:`)
63 for (const subscriber of personalizations) {
64 console.log(' - ', subscriber.to[0].email)
65 }
66
67}());