-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
69 lines (63 loc) · 2.14 KB
/
index.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
"use strict";
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const nodemailer = require("nodemailer");
const { google } = require("googleapis");
admin.initializeApp();
exports.sendemail = functions.https.onCall(async (data, context) => {
const OAuth2 = google.auth.OAuth2;
const APP_NAME = "--YOUR APP NAME--";
const clientID = "--YOUR OAUTH CLIENT ID--";
const clientSecret = "--YOUR OAUTH CLIENT SECRET--";
const refreshToken = "--YOUR REFRESH TOKEN--"
// Checking attribute.`
if (!(typeof data.text === "string") || data.text.length === 0) {
// Throwing an HttpsError so that the client gets the error details.
throw new functions.https.HttpsError(
"invalid-argument",
"The function must be called with one arguments containing the message text to add."
);
}
// Checking that the user is authenticated.
if (!context.auth) {
// Throwing an HttpsError so that the client gets the error details.
throw new functions.https.HttpsError(
"failed-precondition",
"The function must be called while authenticated."
);
}
const oauth2Client = new OAuth2(
clientID, //client Id
clientSecret, // Client Secret
"https://developers.google.com/oauthplayground" // Redirect URL
);
oauth2Client.setCredentials({
refresh_token: refreshToken
});
const tokens = await oauth2Client.refreshAccessToken();
const accessToken = tokens.credentials.access_token;
const smtpTransport = nodemailer.createTransport({
service: "gmail",
auth: {
type: "OAuth2",
user: "youremail@gmail.com",
clientId: clientID,
clientSecret: clientSecret,
refreshToken: refreshToken,
accessToken: accessToken
}
});
const mailOptions = {
from: `${APP_NAME} <youremail@gmail.com>`,
to: data.text, //sending to email IDs in app request, please check README.md
subject: `Hello from ${APP_NAME}!`,
text: `Hi,\n Test email from ${APP_NAME}.`
};
smtpTransport.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error.message);
smtpTransport.close();
}
return "mail sent";
});
});