Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

node.js - How to send an html page as email in nodejs

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I have been using this module: https://github.com/andris9/Nodemailer

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 = '[email protected]';
var TO_ADDRESS = '[email protected]';

// create reusable transport method (opens pool of SMTP connections)
var smtpTransport = nodemailer.createTransport("SMTP",{
    service: "Gmail",
    auth: {
        user: "[email protected]",
        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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...