Nodejs发送邮件模板插件node-email-templates的使用

Nodejs发送邮件模板插件node-email-templates的使用
node-email-templates 是一个 Node.js 的库,用于生成和发送带有模板的电子邮件。它允许你将邮件内容分解成可重用的组件,并且支持 HTML 和文本格式。以下是使用 node-email-templates 的基本步骤:

安装依赖

首先,你需要安装 nodemailernode-email-templates 以及 pug(或其他模板引擎)。

npm install nodemailer node-email-templates pug

创建邮件模板

假设你有一个名为 welcome 的邮件模板,位于 views/emails/welcome.pug 文件中。

h1 Welcome to our service!
p You have successfully signed up for our newsletter.

配置并发送邮件

以下是一个简单的示例,展示了如何配置 nodemailer 并使用 node-email-templates 发送带有模板的邮件。

const Email = require('email-templates');
const nodemailer = require('nodemailer');

// 创建一个 nodemailer 运输对象
const transporter = nodemailer.createTransport({
    host: 'smtp.example.com',
    port: 587,
    secure: false, // true for 465, false for other ports
    auth: {
        user: 'your-email@example.com',
        pass: 'your-password'
    }
});

// 初始化 email-templates 实例
const email = new Email({
    views: {
        root: __dirname + '/views/emails', // 模板文件夹路径
        options: {
            extension: 'pug' // 指定模板引擎
        }
    },
    transport: transporter, // 使用 nodemailer 作为传输方式
    send: true, // 是否在调用 email.send() 时自动发送邮件
    juice: true // 如果为 true,则会在发送之前将内联 CSS 转换为行内样式
});

// 发送邮件
email.send({
    template: 'welcome', // 模板名称
    message: {
        from: 'your-email@example.com',
        to: 'recipient@example.com'
    },
    locals: {
        name: 'John Doe' // 模板中的变量
    }
}).then(() => {
    console.log('Email sent!');
}).catch(err => {
    console.error('Error sending email:', err);
});

注意事项

  1. 安全性:请勿在代码中硬编码敏感信息(如邮箱密码)。考虑使用环境变量或配置文件。
  2. 错误处理:确保添加适当的错误处理逻辑,以便在发送邮件失败时能够捕获错误。
  3. 测试:在生产环境中使用前,务必进行充分的测试。

以上就是使用 node-email-templates 发送带模板的邮件的基本步骤。希望这对你有所帮助!


3 回复

当然!node-email-templates 是一个非常方便的 Node.js 插件,用于创建和发送基于模板的电子邮件。首先,你需要安装它以及一些依赖项:

npm install email-templates nodemailer handlebars --save

接下来,你可以这样设置你的邮件发送脚本:

  1. 创建一个 sendEmail.js 文件。
  2. 编写如下代码:
const Email = require('email-templates').Email;
const nodemailer = require('nodemailer');
const Handlebars = require('handlebars');

// 创建Nodemailer传输对象
let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'your-email@gmail.com',
        pass: 'your-password'
    }
});

// 初始化Email实例
let email = new Email({
    views: {
        root: __dirname + '/templates',
        options: {
            extension: 'hbs' // 使用Handlebars作为模板引擎
        }
    },
    transport: transporter,
    send: true,
    app: {} // 你可以在这里传递一些应用上下文
});

// 发送邮件
email.send({
    template: 'welcome', // 模板名
    message: {
        to: 'recipient@example.com'
    },
    locals: {
        username: 'John Doe'
    }
}).then(console.log).catch(console.error);

别忘了创建你的模板文件,比如 welcome.hbs 放在 templates 文件夹中。

这样,你就有了一个基本的框架来发送基于模板的电子邮件了!祝你编程愉快!


node-email-templates 是一个非常方便的 Node.js 模块,用于生成和发送电子邮件。它允许你通过模板来生成邮件内容,从而使得邮件的内容更加动态和可定制化。下面我将向你介绍如何安装这个模块,并且给出一个简单的示例来展示如何使用它。

1. 安装

首先,你需要在你的项目中安装 nodemaileremail-templates

npm install nodemailer email-templates

此外,你可能还需要安装一些模板引擎(如 pugejs),以及它们对应的适配器(比如 pug-email-template):

npm install pug pug-email-template

或者使用 ejs

npm install ejs

2. 基本使用

接下来,我们将创建一个简单的邮件发送功能。这里以 pug 为模板引擎为例。

创建模板文件

假设我们有一个 views 文件夹,其中包含两个 .pug 文件:welcome.puggoodbye.pug

views/welcome.pug

h1 欢迎
p= message

views/goodbye.pug

h1 再见
p= message

编写发送邮件的代码

const nodemailer = require('nodemailer');
const EmailTemplate = require('email-templates').EmailTemplate;
const path = require('path');

// 创建邮件传输对象
let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'your-email@gmail.com',
        pass: 'your-password'
    }
});

// 初始化模板引擎
const welcomeTemplate = new EmailTemplate(path.join(__dirname, 'views', 'welcome.pug'));
const goodbyeTemplate = new EmailTemplate(path.join(__dirname, 'views', 'goodbye.pug'));

async function sendWelcomeEmail(email, name) {
    const data = { message: `欢迎来到我们的平台,${name}!` };
    return await sendEmail(welcomeTemplate, email, data);
}

async function sendGoodbyeEmail(email, name) {
    const data = { message: `感谢您的访问,${name}。希望您再次光临!` };
    return await sendEmail(goodbyeTemplate, email, data);
}

async function sendEmail(template, to, locals) {
    const result = await template.render(locals);
    const mailOptions = {
        from: 'your-email@gmail.com',
        to,
        subject: '主题',
        html: result.html
    };

    return await transporter.sendMail(mailOptions);
}

// 使用
sendWelcomeEmail('recipient@example.com', 'John Doe')
    .then(info => console.log('Email sent:', info))
    .catch(error => console.error('Error sending email:', error));

上述代码展示了如何使用 node-email-templates 来渲染 Pug 模板,并通过 nodemailer 发送邮件。你可以根据需要修改模板路径、邮件服务配置等信息。

node-email-templates 是一个基于 Node.js 的库,用于简化邮件模板的处理。使用时,首先需要安装 nodemailernode-email-templates

npm install nodemailer email-templates

然后,创建模板目录和相应的 HTML 文件。接下来,编写代码来渲染和发送邮件:

const nodemailer = require('nodemailer');
const Email = require('email-templates').Email;

let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'your-email@gmail.com',
        pass: 'your-password'
    }
});

new Email({
    transport: transporter,
    send: true,
    templateDir: __dirname + '/templates',
});

Email.send({
    template: 'welcome',  // 模板文件名
    message: {
        from: 'your-email@gmail.com'
    },
    locals: {
        name: 'John Doe'  // 传递给模板的数据
    }
});

确保配置好 Gmail 或其他 SMTP 服务。

回到顶部