如何在nodejs中将html页面作为电子邮件发送 [英] How to send an html page as email in nodejs
问题描述
我最近开始编写我的第一个 node.js.我在 node 中找不到任何能够将 html 页面作为电子邮件发送的模块.请帮忙,谢谢!
I recently started programming my first node.js. I can't find any modules from node that is able to send html page as email. please help, thanks!
推荐答案
我一直在使用这个模块:https://github.com/andris9/Nodemailer
I have been using this module: https://github.com/andris9/Nodemailer
更新示例(使用 express 和 nodemailer),包括从文件系统获取 index.jade 模板并将其作为电子邮件发送:
Updated example(using express and nodemailer) that includes getting index.jade template from the file system and sending it as an email:
var _jade = require('jade');
var fs = require('fs');
var nodemailer = require("nodemailer");
var FROM_ADDRESS = 'foo@bar.com';
var TO_ADDRESS = 'test@test.com';
// create reusable transport method (opens pool of SMTP connections)
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "bar@foo.com",
pass: "PASSWORD"
}
});
var sendMail = function(toAddress, subject, content, next){
var mailOptions = {
from: "SENDERS NAME <" + FROM_ADDRESS + ">",
to: toAddress,
replyTo: fromAddress,
subject: subject,
html: content
};
smtpTransport.sendMail(mailOptions, next);
};
exports.index = function(req, res){
// res.render('index', { title: 'Express' });
// specify jade template to load
var template = process.cwd() + '/views/index.jade';
// get template from file system
fs.readFile(template, 'utf8', function(err, file){
if(err){
//handle errors
console.log('ERROR!');
return res.send('ERROR!');
}
else {
//compile jade template into function
var compiledTmpl = _jade.compile(file, {filename: template});
// set context to be used in template
var context = {title: 'Express'};
// get html back as a string with the context applied;
var html = compiledTmpl(context);
sendMail(TO_ADDRESS, 'test', html, function(err, response){
if(err){
console.log('ERROR!');
return res.send('ERROR');
}
res.send("Email sent!");
});
}
});
};
我可能会将邮件程序部分移到它自己的模块中,但我在这里包含了所有内容,以便您可以一起查看.
I'd probably move the mailer part to its own module but I included everything here so you can see it all together.
这篇关于如何在nodejs中将html页面作为电子邮件发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!