Files
appointment_to_examiner/server/routes/emailRoutes.js
2025-01-29 02:52:43 +05:30

78 lines
2.4 KiB
JavaScript

const express = require("express");
const nodemailer = require("nodemailer");
const fs = require("fs");
const multer = require("multer");
const router = express.Router();
// Setup multer for handling file uploads
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./"); // Save to the current directory (you can customize this)
},
filename: function (req, file, cb) {
cb(null, file.originalname); // Use the original file name
},
});
const upload = multer({ storage });
// Route to handle email sending with file attachment
router.post("/", upload.single("file"), async (req, res) => {
const { teacher, fileName, recipientEmail } = req.body;
if (!teacher || !fileName || !recipientEmail || !req.file) {
return res.status(400).json({ error: "Missing required fields or file" });
}
// Configure Nodemailer transporter
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: "swdc.ate@gmail.com", // Replace with your email
pass: "umlc hbkr dpga iywd", // Replace with your app-specific password or token
},
connectionTimeout: 15000,
greetingTimeout: 15000,
socketTimeout: 15000,
});
// Email options
const mailOptions = {
from: "SWDC Admin <swdc.ate@gmail.com>", // Replace with your email
to: recipientEmail,
subject: `Examination Appointments for ${teacher}`,
text: `Dear Sir/Madam,
Please find attached the Excel sheet regarding various appointments for the May-June 2024 Examination. Kindly find the tick mark (√) for the respective appointments.
Note: Kindly download the Excel sheet to view the hidden columns referring to the Scheme and other information.
If you have any queries, please contact the H.O.D or the Examination In-charge.
Your cooperation regarding the upcoming examination duties is highly solicited.`,
attachments: [
{
filename: fileName,
path: req.file.path, // Use the uploaded file's path
},
],
};
try {
// Send email
await transporter.sendMail(mailOptions);
// Delete the temporary file after sending the email
fs.unlinkSync(req.file.path);
res.status(200).json({ message: "Email sent successfully" });
} catch (error) {
console.error("Error sending email:", error);
res.status(500).json({ error: "Failed to send email" });
}
});
module.exports = router;