-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
100 lines (94 loc) · 2.66 KB
/
app.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
// app.js
require("dotenv").config();
const express = require("express");
const app = express();
const qr = require("qrcode");
const path = require("path");
const nodemailer = require("nodemailer");
app.set("view engine", "ejs");
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "public")));
const transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 587,
secure: false, // false for TLS, true for SSL
auth: {
user: process.env.GMAIL_USER,
pass: process.env.GMAIL_PASS,
},
});
// Route to render index.ejs
app.get("/", (req, res) => {
res.render("index", { qrCodeUrl: null });
});
// Route to handle form submission and generate QR code
app.post("/generate", async (req, res) => {
try {
const url = req.body.url;
const qrCodeUrl = await generateQRCode(url);
res.render("index", { qrCodeUrl });
} catch (err) {
res.status(500).send("Error generating QR code");
}
});
app.post("/send", async (req, res) => {
//calls sendEmailWithQR
try {
const email = req.body.email;
const qrCodeUrl = req.body.qrCodeUrl;
console.log("Sending email to:", email);
console.log("QR code URL:", qrCodeUrl);
await sendEmailWithQR(email, qrCodeUrl);
res.send("QR Code sent to your email!");
} catch (err) {
console.error(err);
res.status(500).send("Error sending email");
}
});
// Function to generate QR code
async function generateQRCode(url) {
try {
const qrCodeUrl = await qr.toDataURL(url);
return qrCodeUrl;
} catch (err) {
throw err;
}
}
async function fetchImage(url) {
try {
// Assuming url is a base64 encoded image URL, you might need to modify this based on your QR code generation logic
const data = url.split(",")[1];
return Buffer.from(data, "base64");
} catch (err) {
throw err;
}
}
async function sendEmailWithQR(email, qrCodeUrl) {
try {
const qrImage = await fetchImage(qrCodeUrl);
const info = await transporter.sendMail({
from: process.env.GMAIL_USER,
to: email,
subject: "Your QR Code and Image",
html: `
<h3>Dear user, here is your QR code:</h3>
<br />
<img src="cid:qrCodeUrl" alt="QR Code">
`,
attachments: [
{
filename: "qrcode.png",
content: qrImage,
encoding: "base64",
cid: qrCodeUrl, // should match cid value in html img src
},
],
});
console.log("Email sent: %s", info.messageId);
} catch (err) {
console.error(err);
throw err;
}
}
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));