问题
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