Using Email Templates from MongoDB in Node.js [closed]

99封情书 提交于 2020-03-03 20:59:35

问题


I would like to know that how can I use email templates saved in MongoDB to send email in Node.js. The email schema would be like this -

var emailSchema = new Schema({
    senderMail: String,
    senderName: String,
    template-name: String,
    template: String
});

senderMail and senderName is what I want to send for that template. For example, I would like to send user password reset template, I want to send as MyName and email would be noreply@domain.com. template-name will be something like user-registration, forget-password, subscription or anything it can be. In template, there will be email template code written in swig or ejs so that we can use dynamic values like {{ email }}.

You may ask why I must use it when there are packages like node-email-templates, but rather than using many folders inside application for email templates, I prefer to use email templates saved in Database and send.

If there are better options, or something wrong, please point it out and get me right. Thank you.

Note. I am currently using Mandrill for sending email.


回答1:


My recomendation is:

http://www.nodemailer.com/

I am using template as you want to but I am embed it my code. So you just need an db select operation from get template from database. In this way you just need one .js file to send mail. I will provide you my mail function. Also you can store 'subject' field at database.

module.exports = function(templateName,to) {

var mailer = require('nodemailer');

var transporter = mailer.createTransport({
    service: 'Gmail',
    auth: {
        user: '***@gmail.com',
        pass: '****'
    }
});

//-- Get your html body from database

db.template.findOne({templateName : templateName},function(err,template){
var mailOptions = {
    from: template.senderMail, // sender address
    to: to, // list of receivers
    subject: template.subject, // Subject line
    html: template.template// html body
};
}); //-- this line can be change


transporter.sendMail(mailOptions, function (error, info) {
    if (error) {
        console.log('mail error' + error);
        return error;
    } else {
        console.log('mail info' + info);
        return 'OK';
    }
});
}

And you can use like this:

var mailer = require('../mailoperations/mailer'); //-- Your js file path
mailer('register', 'to@to.com');

I dont know good or bad ,store this thing at database but it seems more controllable this way. Hope this help.



来源:https://stackoverflow.com/questions/29136326/using-email-templates-from-mongodb-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!