如何在nodejs中将html页面作为电子邮件发送

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21654051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:49:39  来源:igfitidea点击:

How to send an html page as email in nodejs

node.jsexpresshtml-email

提问by user3044147

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!

我最近开始编写我的第一个 node.js。我在 node 中找不到任何能够将 html 页面作为电子邮件发送的模块。请帮忙,谢谢!

回答by Ryan

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

我一直在使用这个模块: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:

更新示例(使用 express 和 nodemailer),包括从文件系统获取 index.jade 模板并将其作为电子邮件发送:

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.

我可能会将邮件程序部分移到它自己的模块中,但我在这里包含了所有内容,以便您可以一起查看。

回答by IT Vlogs

You can use nodemailerand nodemailer-express-handlebarsmodules do this:

您可以使用nodemailernodemailer-express-handlebars模块执行此操作:

var nodemailer = require('nodemailer');
var mailerhbs = require('nodemailer-express-handlebars');

var mailer = nodemailer.createTransport({
    service: Gmail,  // More at https://nodemailer.com/smtp/well-known/#supported-services
    auth: {
        user: [[email protected]], // Your email id
        pass: [PASSWORD] // Your password
    }
});

mailer.use('compile', mailerhbs({
    viewPath: 'templates/default/emails', //Path to email template folder
    extName: '.hbs' //extendtion of email template
}));

In router post you can use:

在路由器帖子中,您可以使用:

mailer.sendMail({
            from: 'Your name [email protected]',
            to: user.local.email,
            subject: 'Reset your password',
            template: 'password_reset', //Name email file template
            context: { // pass variables to template
                hostUrl: req.headers.host,
                customeName: user.info.firstname + ' ' + user.info.lastname,
                resetUrl: req.headers.host + '/users/recover/' + token,
                resetCode: token
            }
        }, function (err, response) {
            if (err) {
                res.send('Error send email, please contact administrator to best support.');
            }
            res.send('Email send successed to you email' + req.body.email + '.');
            done(err, 'done');
        });

In hbs template you can use variables:

在 hbs 模板中,您可以使用变量:

{{var from context}}

hope blocks of code to help you.

希望代码块能帮助你。