Pass variable to html template in nodemailer

前端 未结 8 2170
礼貌的吻别
礼貌的吻别 2021-01-30 16:45

I want to send email with nodemailer using html template. In that template I need to inject some dynamically some variables and I really can\'t do that. My code:



        
8条回答
  •  隐瞒了意图╮
    2021-01-30 17:28

    For those using pug as templating engine

    Just a quick way to render a template in a separate file using pug's render function:

    // function to send an e-mail. Assumes you've got nodemailer and pug templating engine installed. 
    // transporter object relates to nodemailer, see nodemailer docs for details
    const nodemailer = require('nodemailer');
    const pug = require('pug');
    function send_some_mail(iterable){
    var message = {
      from: 'from@example.com',
      to: 'to@example.com',
      subject: 'Message title',
      html: pug.renderFile(__dirname + 'path_to_template.pug', {iterable: iterable})
    };
    transporter.sendMail(message, function(err, info){...})
    }
    
    // template.pug
    each item in iterable
    li
      p #{item.name}
    

    See https://pugjs.org/api/getting-started.html for further details. Note that this will cause template re-compilation every time a message is sent. That is fine for occasional e-mail deliveries. If you send tons of e-mails, you can cache the compiled template to work around that. Check out pug docs for that set up if you need it.

提交回复
热议问题