Configure HTML variable inside Nodemailer html

Asked

Viewed 149 times

5

I need to send an email using Nodemailer, and I need to send email with html, but I’m not able to set the variables directly inside the email HTML, I’ve tried the replace() and did not succeed.

server.route({
path: '/enviar',
method: 'post',
handler: function (request, reply) {
    console.log(request.payload);
    let usuario = '[email protected]';
    let senha = 'senha';
    let transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: usuario,
            pass: senha
        }
    });

    let receiver = request.payload.destinatario;
    let ass = request.payload.assunto;
    let email = request.payload.texto;
    let mailOptions = {
        from: usuario,
        to: receiver,
        subject: ass,
        text: email,
        html:'<html><head><title>Titulo</title></head><body> <div 
        id="assunto"></div></body></html>',
        attachments: []
    };
    let nomes = fs.readdirSync(__dirname + '/uploads');
    for (let n = 0; n < nomes.length; n++) {
  mailOptions.attachments.unshift({
    filename: nomes[n],
    path: __dirname + '/uploads/' + nomes[n]
  })
}
    transporter.sendMail(mailOptions, function (err, info) {
        if (err) {
            console.log(err)
        } else {
            console.log('Enviado! ' + info.response);
            for (let l = 0; l < mailOptions.attachments.length; l++){
                del.sync(__dirname + '/uploads/' + 
                mailOptions.attachments[l].filename)
            }
            return reply.response('Enviou')

        }
    });
}
});

How do I put the subject inside the div with the id=assunto

1 answer

1

You can use Template Strings or concatenate.

let titulo = 'Titulo do E-mail';
let ass = 'Assunto do E-mail';

// Template Strings
let mailOptions = {
    html: `<html><head><title>${titulo}</title></head><body> <div id="assunto">${ass}</div></body></html>`,
};

console.log(mailOptions.html);

// Concatenar
mailOptions = {
    html: '<html><head><title>'+titulo+'</title></head><body> <div id="assunto">'+ass+'</div></body></html>'
};

console.log(mailOptions.html);

Reference

Browser other questions tagged

You are not signed in. Login or sign up in order to post.