-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
228 lines (188 loc) · 7 KB
/
index.js
File metadata and controls
228 lines (188 loc) · 7 KB
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import express from "express";
import session from "express-session";
import env from "dotenv";
import passport from "passport";
import { Strategy as GoogleStrategy } from "passport-google-oauth20";
import { google } from "googleapis";
import multer from "multer";
import fs from "fs";
import csv from "csv-parser";
const app=express();
env.config();
app.use(express.urlencoded({ extended: true })); // To parse form data
app.use(express.json()); // To parse JSON data
app.use(session({
secret: process.env.EXPRESS_SESSION_SECRET,
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 1000*60*60
}
}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser((user, done)=>{
return done(null, user);
});
passport.deserializeUser((user, done)=>{
return done(null, user);
});
passport.use("google", new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "https://bulk-email-sender-656561414793.asia-south1.run.app/auth/google/callback",
passReqToCallback : true,
accessType: "offline",
prompt: 'consent'
}, (request, accessToken, refreshToken, profile, done)=>{
profile.token = accessToken;
profile.refreshToken = refreshToken;
// console.log(profile);
return done(null, profile);
}));
async function sendmail(req, res, data, template, subjectTemplate) {
const { token, refreshToken } = req.user;
try {
// Create OAuth2 client
const oAuth2Client = new google.auth.OAuth2(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET,
"https://bulk-email-sender-656561414793.asia-south1.run.app/auth/google/callback"
);
oAuth2Client.setCredentials({
access_token: token,
refresh_token: refreshToken,
});
const gmail = google.gmail({ version: "v1", auth: oAuth2Client });
// Map over each person and send personalized email
for (let person of data) {
let personalizedMessage = template;
let personalizedSubject = subjectTemplate;
// Replace each header field with the corresponding value in the CSV row for body
for (let [key, value] of Object.entries(person)) {
const regex = new RegExp(`{{${key}}}`, 'g'); // Create a regex to match {{field}} format
personalizedMessage = personalizedMessage.replace(regex, value);
personalizedSubject = personalizedSubject.replace(regex, value);
}
// If there are any placeholders left unreplaced (i.e., user entered wrong field)
if (personalizedMessage.match(/{{.*?}}/g) || personalizedSubject.match(/{{.*?}}/g)) {
return res.status(400).send("Invalid fields in template or subject.");
}
const email = [
"Content-Type: text/plain; charset=utf-8",
"MIME-Version: 1.0",
"Content-Transfer-Encoding: 7bit",
`to: ${person.email}`, // Assuming the 'email' field exists in CSV
`subject: ${personalizedSubject}`, // Personalized subject
"",
personalizedMessage,
].join("\n");
// Base64 encode the email
const encodedMessage = Buffer.from(email)
.toString("base64")
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
// Send the email using Gmail API
await gmail.users.messages.send({
userId: "me",
requestBody: {
raw: encodedMessage,
},
});
console.log(`Mail sent to ${person.email}`);
}
res.send("Emails sent successfully!");
} catch (error) {
console.error("Error sending email:", error);
res.status(500).send("Error sending email.");
}
}
//csv file handling
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './uploads/');
},
filename: (req, file, cb) => {
cb(null, "csvfile.csv");
}
});
const upload = multer({ storage });
// CSV File Processing
function readfile() {
return new Promise((resolve, reject) => {
const results = [];
let headers = [];
fs.createReadStream('./uploads/csvfile.csv')
.pipe(csv())
.on('headers', (headerList) => {
headers = headerList; // Store headers
})
.on('data', (data) => results.push(data))
.on('end', () => resolve({ headers, results }))
.on('error', (err) => reject(err));
});
}
app.post("/sendmail", upload.single('file'), async (req, res) => {
if(req.isAuthenticated()){
const { headers, results } = await readfile();
res.render('loggedin.ejs', {
name: req.user.displayName,
headers: headers // Send headers to frontend
});
}
else{
res.redirect("/");
}
});
app.post("/sendmailtemplate", async (req, res) => {
if (req.isAuthenticated()) {
try {
const { headers, results } = await readfile(); // Assuming you return headers + data from readfile()
const template = req.body.template;
const subject = req.body.subject;
// Validate if all fields in the subject and template exist in CSV headers
const templateFields = template.match(/{{(.*?)}}/g) || [];
const subjectFields = subject.match(/{{(.*?)}}/g) || [];
const allFields = [...templateFields, ...subjectFields];
const invalidFields = allFields.filter(field => !headers.includes(field.replace(/{{|}}/g, '')));
if (invalidFields.length > 0) {
return res.status(400).send(`Invalid fields: ${invalidFields.join(', ')}`);
}
// Send mail with personalized subject and content
await sendmail(req, res, results, template, subject);
} catch (error) {
console.error("Error processing template:", error);
res.status(500).send("Error processing template.");
}
} else {
res.redirect("/");
}
});
app.get("/auth/google", passport.authenticate("google", { scope: ["profile", "email", "https://www.googleapis.com/auth/gmail.send"], accessType: "offline" , prompt: "consent"}));
app.get("/auth/google/callback", passport.authenticate("google", {
failureRedirect: "/",
successRedirect : "/afterlogin"
}));
app.get("/afterlogin", (req, res)=>{
if (req.isAuthenticated()) {
res.render("loggedin.ejs", {
name: req.user.displayName
});
} else {
res.redirect('/');
}
});
app.get("/auth/google/logout", (req, res)=>{
req.logout(function (err) {
if (err) {
return next(err);
}
res.redirect("/");
});
});
app.use(express.static("public"));
app.get("/", (req, res)=>{
res.sendFile("index.html");
});
app.listen(3000);