Skip to content

Instantly share code, notes, and snippets.

@Octagon-simon
Created March 8, 2024 17:17

Revisions

  1. Octagon-simon created this gist Mar 8, 2024.
    64 changes: 64 additions & 0 deletions sendEmail.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,64 @@
    import fs from 'fs';
    import nodemailer from 'nodemailer';

    async function sendEmail(data) {
    try {
    //destructure
    const { dataToReplace, emailSubject, recipientEmail } = data;

    // Replace with the actual path to your template file
    const templatePath = `./templates/loginTemplate`;

    // Read the template file
    let templateContent = fs.readFileSync(templatePath, 'utf8');

    // Replace placeholders with actual values
    Object.entries(dataToReplace).forEach(([placeholder, value]) => {
    const regex = new RegExp(`{{${placeholder}}}`, 'g');
    templateContent = templateContent.replace(regex, value);
    });

    const transporter = nodemailer.createTransport({
    host: '[email protected]',
    port: 465,
    auth: {
    user: '[email protected]',
    pass: '[email protected]'
    }
    });

    const mailOptions = {
    from: '[email protected]',
    replyTo: '[email protected]',
    to: recipientEmail,
    subject: emailSubject,
    html: templateContent
    };

    //send the email
    const info = await transporter.sendMail(mailOptions);
    //return response
    return info.response;
    } catch (error) {
    console.log(error);
    }
    }

    //construct the payload object
    const emailPayload = {
    dataToReplace: {
    username: 'Octagon',
    ipAddress: '127.0.0.1',
    location: 'Lagos, Nigeria'
    },
    emailSubject: 'Account Login Notification',
    recipientEmail: '[email protected]'
    }

    //handle Promise with .then
    sendEmail(emailPayload)
    .then((res) => console.log(res))
    .catch((err) => console.log(err))

    //or use await
    await sendEmail(emailPayload)