Experimenting with Node.js - Sending Email using the html template
- Published on
-  • hourglass-not-done3 mins read•eye––– views
Photo by Chris Ried on Unsplash
javascript code to convert the image to base64
import fs from 'fs/promises'; // Import fs.promisesimport path from 'path';import { fileURLToPath } from 'url';import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);
async function imageToBase64(imageFilePath) {  try {    const imageBuffer = await fs.readFile(imageFilePath);    const base64String = imageBuffer.toString('base64');
    const txtFilePath = imageFilePath.replace(/\.[^/.]+$/, '.txt');    await fs.writeFile(txtFilePath, base64String);    console.log(`Image converted to base64 and saved to ${txtFilePath}`);  } catch (error) {    console.error('Error in imageToBase64:', error);  }}
async function listImageFiles(folderPath) {  try {    const files = await fs.readdir(folderPath);
    const imageFiles = files.filter((file) => {      const ext = path.extname(file).toLowerCase();      return ext === '.jpg' || ext === '.jpeg' || ext === '.png';    });
    console.log('Image files (JPEG and PNG):');    imageFiles.forEach(async (file) => {        const imagePath = path.join(folderPath, file);        await imageToBase64(imagePath);    });
    return imageFiles; // Return the array of image files if needed
  } catch (error) {    console.error('Error in listImageFiles:', error);    return []; // Return empty array in case of error  }}
async function main(){    const folderPath = __dirname;    await listImageFiles(folderPath);}
main();javascript code to send an email
import fs from 'fs/promises';import path from 'path';import { parse } from 'csv-parse';import nodemailer from 'nodemailer';import { fileURLToPath } from 'url';import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);
async function sendEmailsFromCSV(csvFilePath, htmlBodyFilePath, emailConfig) {  try {    const csvFileContent = await fs.readFile(csvFilePath, { encoding: 'utf-8' });    const htmlBodyContent = await fs.readFile(htmlBodyFilePath, {      encoding: 'utf-8',    });
    const transporter = nodemailer.createTransport(emailConfig);
    parse(csvFileContent, {      columns: true,      skip_empty_lines: true,    }, async (err, records) => {      if (err) {        console.error('Error parsing CSV:', err);        return;      }
      for (const record of records) {        const { email, name } = record; // Adjust column names if needed
        if (email && name) {          const personalizedBody = htmlBodyContent.replace(            /\[Attendee_Name\]/g,            name          );
          const mailOptions = {            from: emailConfig.auth.user,            to: email,            subject: 'Event Information', // Change to your desired subject            html: personalizedBody,          };
          try {            const info = await transporter.sendMail(mailOptions);            console.log(`Email sent to ${email}: ${info.messageId}`);          } catch (emailError) {            console.error(`Error sending email to ${email}:`, emailError);          }        } else {          console.warn('Skipping row due to missing email or name:', record);        }      }
      console.log('Email sending process completed.');    });  } catch (error) {    console.error('Error:', error);  }}
// Example Usage:const csvFilePath = path.join(__dirname, 'attendees.csv'); // Path to your CSV fileconst htmlBodyFilePath = path.join(__dirname, 'mkmm-email.html'); // Path to your HTML fileconst emailConfig = {  service: 'gmail', // Or your email service  auth: {    user: 'xxxx@gmail.com', // Replace with your email    pass: 'xxx', // Replace with your password (or app password)  },};
console.log('Starting the email sending process...');
sendEmailsFromCSV(csvFilePath, htmlBodyFilePath, emailConfig);