Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.1 kB
1
Indexable
Never
const nodemailer = require("nodemailer");
const Settings = require("../models/GeneralSettings");

const mailSender = async (email, title, body, attachments, attachmentFileType) => {
  try {
    // Retrieve nodemailerMail and nodemailerPassword from settings
    const settings = await Settings.findOne(); // Assuming you have only one settings document
    const { nodemailerMail, nodemailerPassword } = settings;

    // Create a transporter
    let transporter = nodemailer.createTransport({
      service: "gmail",
      auth: {
        user: nodemailerMail,
        pass: nodemailerPassword
      }
    });

    // Mail options
    const mailOptions = {
      from: "Snapzeee",
      to: email,
      subject: title,
      html: body,
      attachments: []
    };

    // Include attachment if provided

    if(attachmentFileType === "pdf"){

    attachments.map((attachment) => {
      mailOptions.attachments.push({
        filename: "invoice.pdf", // You can customize the filename
        content: attachment,
        encoding: "base64"
      });
    })

    }
    if(attachmentFileType === "jpg"){
      attachments?.map((attachment) => {
        mailOptions.attachments.push({
          filename:  "edited-image.jpg", // You can customize the filename
          content: attachment,
          encoding: "base64"
        });
      })

    }
    // if (attachment ) {
    //   if(attachmentFileType === "pdf"){
    //     mailOptions.attachments.push({
    //       filename: "invoice.pdf", // You can customize the filename
    //       content: attachment,
    //       encoding: "base64"
    //     });
    //   }else{
    //     mailOptions.attachments.push({
    //       filename: "edited-image.jpg", // You can customize the filename
    //       content: attachment,
    //       encoding: "base64"
    //     });
    //   }
      
    // }

    // Send mail
    let info = await transporter.sendMail(mailOptions);

    return info;
  } catch (error) {
    console.log(error.message);
  }
};

module.exports = mailSender;
Leave a Comment