-
Notifications
You must be signed in to change notification settings - Fork 0
/
mailer.js
executable file
·151 lines (142 loc) · 4.54 KB
/
mailer.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
/* eslint-disable no-unused-vars */
import fs from 'fs';
import readline from 'readline';
import { promisify } from 'util';
import mimeMessage from 'mime-message';
import { gmail_v1 as gmailV1, google } from 'googleapis';
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/gmail.send'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';
const readFileAsync = promisify(fs.readFile);
const writeFileAsync = promisify(fs.writeFile);
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback for the authorized client.
*/
async function getNewToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) {
console.error('Error retrieving access token', err);
return;
}
oAuth2Client.setCredentials(token);
writeFileAsync(TOKEN_PATH, JSON.stringify(token))
.then(() => {
console.log('Token stored to', TOKEN_PATH);
callback(oAuth2Client);
})
.catch((writeErr) => console.error(writeErr));
});
});
}
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
async function authorize(credentials, callback) {
const clientSecret = credentials.web.client_secret;
const clientId = credentials.web.client_id;
const redirectURIs = credentials.web.redirect_uris;
const oAuth2Client = new google.auth.OAuth2(
clientId,
clientSecret,
redirectURIs[0],
);
console.log('Client authorization beginning');
// Check if we have previously stored a token.
await readFileAsync(TOKEN_PATH)
.then((token) => {
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
}).catch(async () => getNewToken(oAuth2Client, callback));
console.log('Client authorization done');
}
/**
* Delivers a mail through the user's account.
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
* @param {gmailV1.Schema$Message} mail The message to send.
*/
function sendMailService(auth, mail) {
const gmail = google.gmail({ version: 'v1', auth });
gmail.users.messages.send({
userId: 'me',
requestBody: mail,
}, (err, _res) => {
if (err) {
console.log(`The API returned an error: ${err.message || err.toString()}`);
return;
}
console.log('Message sent successfully');
});
}
/**
* Contains routines for mail delivery with GMail.
*/
export default class Mailer {
static checkAuth() {
readFileAsync('credentials.json')
.then(async (content) => {
await authorize(JSON.parse(content), (auth) => {
if (auth) {
console.log('Auth check was successful');
}
});
})
.catch((err) => {
console.log('Error loading client secret file:', err);
});
}
static buildMessage(dest, subject, message) {
const senderEmail = process.env.GMAIL_SENDER;
const msgData = {
type: 'text/html',
encoding: 'UTF-8',
from: senderEmail,
to: [dest],
cc: [],
bcc: [],
replyTo: [],
date: new Date(),
subject,
body: message,
};
if (!senderEmail) {
throw new Error(`Invalid sender: ${senderEmail}`);
}
if (mimeMessage.validMimeMessage(msgData)) {
const mimeMsg = mimeMessage.createMimeMessage(msgData);
return { raw: mimeMsg.toBase64SafeString() };
}
throw new Error('Invalid MIME message');
}
static sendMail(mail) {
readFileAsync('credentials.json')
.then(async (content) => {
await authorize(
JSON.parse(content),
(auth) => sendMailService(auth, mail),
);
})
.catch((err) => {
console.log('Error loading client secret file:', err);
});
}
}