Reusable Email structure in nodejs

Viewed 21

I need to send out emails to support team and users depending on the outcome of certain business functions written in nodejs. I am using the below approach.

let emailStartTags = "<html><body><p>Hi Team,</p><p>";
const emailEndTags = "</p><p>Thanks,<br>ABC Support</p></body></html>"  
const Subject = `DEV Order No 1234`
let emailContent="";
emailContent+=emailStartTags;
const s3FilesList = await this.getFilesFromS3Directory(directoryName)
emailContent+=<p>S3 files are ${s3FilesList}<p>
emailContent+=emailEndTags

await this.sendEmail(emailContent,Subject,From,To);

Is there any other way I can compose the email content better instead of hardcoding like above. May be using a email class with getters setters. If so, can you please help me with some reference.

1 Answers

I think you are using that wrongly now. You shouldn't use the dynamic email content like that. It won't be practice solution for you. I used nodemailer to post a email on nodejs. It is one of the most popular packages to post a email.

You can use like this.

mailer.ts:

import nodemailer from "nodemailer";

export default nodemailer.createTransport({
    host: "example_host",
    port: 2525,
    auth: {
        user: process.env.MAILTRAP_AUTH_USER,
        pass: process.env.MAILTRAP_AUTH_PASSWORD
    }
});

compile-email.ts for dynamic html:

import * as path from 'path';
import * as fs from 'fs';
import * as handlebars from 'handlebars';

export default (emailPath: string, replacements: object = {}): string => {
    const filePath = path.join(__dirname, `../../views/emails/${emailPath}.html`);
    const source = fs.readFileSync(filePath, 'utf-8').toString();
    const template = handlebars.compile(source);
    return template(replacements);
};

And an example job. Each post email proccess is a job. For example, send-register-code.ts:

import mailer from "../utils/email/mailer";
import compileEmail from "../utils/email/compile-email";

export default async (to: string, replacements: object) => {
    await mailer.sendMail({
        to,
        from: 'keymanager@example.com',
        subject: "Register Code",
        html: compileEmail('register-code-email', replacements),
    });
}

register-code.html:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
Register Code: {{code}}
</body>
</html>

And lastly, how can you that job ? For example for using send-register-code job:

import sendRegisterCode from '../../jobs/send-register-code';

sendRegisterCode(email, { code });

I think you will have a structure clearer than now to post email. I hope it would be helpful you

Related