使用email-templates模块解析邮件模板,然后借助于NodeMailer模块使用NodeJS来发邮件,当然,在使用之前首先你必须先安装email-templates和NodeMailer模块。使用时直接导入模板,最后将邮件发送出去。

添加模板依赖
"ejs": "^2.3.1",
"email-templates": "^1.2.0",
添加邮件发送依赖
"nodemailer": "^1.3.0",
项目结构:
BFB4763E-D6CE-4EC8-A490-7E8FC44BB6CC
邮件发送代码email_service.js
var nodemailer = require('nodemailer');

//https://github.com/andris9/Nodemailer
var transporter = nodemailer.createTransport($config.emailOptions);

//https://github.com/niftylettuce/node-email-templates
var path = require('path')
    , templatesDir = path.join(__dirname, '../templates')
    , emailTemplates = require('email-templates');

/**
 * mailSend
 * @param mailOptions https://github.com/andris9/Nodemailer
 * @param callback
 */

exports.mailSendByTemplate = function (mailOptions, callback) {
    // send mail with defined transport object

    emailTemplates(templatesDir, function (err, template) {

        template(mailOptions.templateName, mailOptions.templateData, function (err, html, text) {

            mailOptions.html = html;
            transporter.sendMail(mailOptions, function (error, info) {
                if (error) {
                    //console.log(error);
                    callback(false, error);
                } else {
                    callback(true, info.response);
                    //console.log('Message sent: ' + info.response);
                }
            });

        });
    });
};

var config = {

    /**
     * 生产环镜
     */
    production: {
        
    },

    /**
     * 开发环镜
     */
    development: {
        emailOptions: {
            host: 'smtp.163.com',
            secure: true,
            auth: {
                user: 'wzqdemo@163.com',
                pass: '*********'
            },

            from: 'wzqdemo Test<wzqdemo@163.com>'
            
        }
        morgan: 'dev',
        moment: 'zh-cn',
        ...
    },

    /**
     * 返回或设置当前环镜
     */
    evn: function () {
        global.$config = this.development;

        return global.$config;
    }
};

module.exports = config.evn();
模板文件temp_test/html.ejs
<h1>You are invited to our weekly pasta dinner!</h1>
<h2>This week's pasta is: <%= msg %></h2>
<h3>We hope to see you there!</h3>


<ul>
    <% for(var i=0; i<supplies.length; i++) {%>
    <li><%= supplies[i].pasta %></li>
    <% } %>
</ul>
 使用方法
var mailOptions = {
    from: $config.emailOptions.from, // sender address
    to: 'haleywang@digitalrev.com', // list of receivers
    subject: 'temp test', // Subject line
    templateName: 'temp_test',
    templateData: {msg:'haleywang.com' , supplies: [
        { pasta: 'Spaghetti' },
        { pasta: 'Rigatoni' }
    ]}
};

emialService.mailSendByTemplate(mailOptions, function(success, msg) {
    if(success){
        console.info('Message sent: ' + msg);
    }else{
        console.info(msg);
    }
});