-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreateMail.js
99 lines (87 loc) · 2.13 KB
/
createMail.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
const {google} = require('googleapis');
const mailComposer = require('nodemailer/lib/mail-composer');
class CreateMail {
constructor(auth, to, sub, body, task, attachmentSrc) {
this.me = '[email protected]';
this.task = task;
this.auth = auth;
this.to = to;
this.sub = sub;
this.body = body;
this.gmail = google.gmail({version: 'v1', auth});
this.attachment = attachmentSrc;
}
// Creates the mail body and encodes it to base64 format.
makeBody() {
let mail = new mailComposer({
to: this.to,
html: this.body, // can be changed to play 'text: this.body'
subject: this.sub,
textEncoding: "base64"
});
//Compiles and encodes the mail.
mail.compile().build((err, msg) => {
if (err){
return console.log('Error compiling email ' + error);
}
const encodedMessage = Buffer.from(msg)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
if(this.task === 'mail'){
this.sendMail(encodedMessage);
}
else{
this.saveDraft(encodedMessage);
}
});
}
// Send the message to specified receiver.
sendMail(encodedMessage) {
this.gmail.users.messages.send({
userId: this.me,
resource: {
raw: encodedMessage,
}
}, (err, result) => {
if(err){
return console.log('NODEMAILER - The API returned an error: ' + err);
}
console.log("NODEMAILER - Sending email reply from server:", result.data);
});
}
// Saves the draft.
saveDraft(encodedMessage) {
this.gmail.users.drafts.create({
'userId': this.me,
'resource': {
'message': {
'raw': encodedMessage
}
}
})
.then(res => console.log("Draft created : ", res.data))
}
// Deletes the draft.
deleteDraft(id) {
this.attachment.gmail.users.drafts.delete({
id: id,
userId: this.me
});
}
//Lists all drafts.
listAllDrafts() {
this.gmail.users.drafts.list({
userId: this.me
}, (err, res) => {
if(err) {
console.log(err);
}
else {
console.log(res.data);
}
});
}
}
module.exports = CreateMail;