-
Notifications
You must be signed in to change notification settings - Fork 0
/
mail.js
105 lines (93 loc) · 2.85 KB
/
mail.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
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
97
98
99
100
101
102
103
104
105
const {google} = require('googleapis');
const mailComposer = require('nodemailer/lib/mail-composer');
const Attachments = require('./attachments.js');
const fs = require('fs');
class Mail{
constructor(auth, contact){
const { emailAddresses, engagementManagers, employerGroupId, companyName } = contact;
this.gmail = google.gmail({version: 'v1', auth});
this.auth = auth;
this.from = '[email protected]';
this.to = emailAddresses;
this.cc = engagementManagers;
this.employerGroupId = employerGroupId;
this.company = companyName;
this.task = 'draft';
this.subject = `November 2019 Invoice for ${companyName}`;
try {
this.body = fs.readFileSync('email_body.html', 'utf8');
} catch(e) {
throw(`Error: ${e}`);
}
}
createMail(){
// Get attachments, compile, encode, and send mail.
let self = this;
let attachments = new Attachments(this.employerGroupId);
attachments.encodedList(function(encodedAttachments){
self.composeMail(self, encodedAttachments).compile().build((err, msg) => {
// Do not generate invoice if attachments are missing.
if(err){
return console.log(`Error compiling email: ${err}`);
} else if(encodedAttachments.length < 2){
return console.log(`Will not generate invoice: Attachments missing for ${self.company}`);
}
const encodedMessage = Buffer.from(msg)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
// If the task is 'mail', send automatically. Otherwise, create draft.
if(self.task === 'mail'){
self.sendMail(encodedMessage);
} else {
self.saveDraft(encodedMessage);
}
});
});
}
// Compose mail.
composeMail(self, attachments){
return new mailComposer({
to: self.to,
cc: self.cc,
html: self.body,
subject: self.subject,
textEncoding: 'base64',
attachments: attachments
});
}
// Send the message to the specified recipient.
sendMail(encodedMessage){
this.gmail.users.messages.send({
userId: this.from,
resource: {
raw: encodedMessage
}
}, (err, result) => {
if(err){
return console.log(`The API returned an error: ${err}`);
} else {
console.log(`Sending email reply from server: ${result.data}`);
}
});
}
// Save a draft.
saveDraft(encodedMessage){
this.gmail.users.drafts.create({
userId: this.from,
resource: {
message: {
raw: encodedMessage
}
}
}, (err, result) => {
if(err){
return console.log(`Error creating draft for ${this.company}: ${err}`);
} else {
console.log(`Draft created successfully for ${this.company}`);
}
});
}
}
module.exports = Mail;