How to send an html page as email in nodejs

后端 未结 2 1424
Happy的楠姐
Happy的楠姐 2020-12-01 10:01

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!

2条回答
  •  一整个雨季
    2020-12-01 10:31

    You can use nodemailer and nodemailer-express-handlebars modules do this:

    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: [USERNAME@gmail.com], // 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 username@domain.com',
                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:

    {{var from context}}
    

    hope blocks of code to help you.

提交回复
热议问题