-
Notifications
You must be signed in to change notification settings - Fork 1
/
gmail.js
36 lines (31 loc) · 1.13 KB
/
gmail.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
const { google } = require('googleapis');
const MailComposer = require('nodemailer/lib/mail-composer');
const credentials = require('./credentials.json');
const tokens = require('./token.json');
const getGmailService = () => {
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
oAuth2Client.setCredentials(tokens);
const gmail = google.gmail({ version: 'v1', auth: oAuth2Client });
return gmail;
};
const encodeMessage = (message) => {
return Buffer.from(message).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
};
const createMail = async (options) => {
const mailComposer = new MailComposer(options);
const message = await mailComposer.compile().build();
return encodeMessage(message);
};
const sendMail = async (options) => {
const gmail = getGmailService();
const rawMessage = await createMail(options);
const { data: { id } = {} } = await gmail.users.messages.send({
userId: 'me',
resource: {
raw: rawMessage,
},
});
return id;
};
module.exports = sendMail;