Pass variable to html template in nodemailer

前端 未结 8 2194
礼貌的吻别
礼貌的吻别 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:25

    You can use a Web Request to build an html template using handlebars or any other engine.

    Create a template

    First you must create an html template for the email body. In this example I used a handlebars hbs file.

    Do your design stuff with html and add the variables that you will need in the message:

       
       
        
            
            
            Welcome Email Template
        
        
         

    Hi {{data.name}}

    Create a template request

    You must create the access to this view. Then a request is created where we can send the template name as an url parameter to make the request parameterizable for other templates.

    const web = express.Router()
    
    web.post('/template/email/:template', function(req, res) {
      res.render(`templates/email/${req.params.template}`, {
        data: req.body        
      })
    })
    

    Mail function

    Finally you can send the email after making the request to the template. You can use a function like the following:

    const nodemailer = require('nodemailer')
    const request = require("request")
    
    function sendEmail(toEmail, subject, templateFile) {
        var options = {
            uri: `http://localhost:3000/template/email/${templateFile}`,
            method: 'POST',
            json: { name: "Jon Snow" } // All the information that needs to be sent
        };  
        request(options, function (error, response, body) {
            if (error) console.log(error)
            var transporter = nodemailer.createTransport({
                host: mailConfig.host,
                port: mailConfig.port,
                secure: true,
                auth: {
                    user: mailConfig.account,
                    pass: mailConfig.password
                }
            })
            var mailOptions = {
                from: mailConfig.account,
                to: toEmail,
                subject: subject,
                html: body
            }       
            transporter.sendMail(mailOptions, function(error, info) {
                if (error) console.log(error)
            })
        })
    }
    

提交回复
热议问题