Pass variable to html template in nodemailer

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

    I use it in all my projects. more clean and up to date and understandable. callback hell doesn't exist. sendMail.ts The html file reads with handlebar, puts the relevant variables into the contents, and sends.

    import * as nodemailer from 'nodemailer';
    import * as handlebars from 'handlebars';
    import * as fs from 'fs';
    import * as path from 'path';
    
    export async function sendEmail(email: string, subject: string, url: string) {
      const filePath = path.join(__dirname, '../emails/password-reset.html');
      const source = fs.readFileSync(filePath, 'utf-8').toString();
      const template = handlebars.compile(source);
      const replacements = {
        username: "Umut YEREBAKMAZ"
      };
      const htmlToSend = template(replacements);
      const transporter = nodemailer.createTransport({
        host: "smtp.mailtrap.io",
        port: 2525, // 587
        secure: false,
        auth: {
          user: "fg7f6g7g67",
          pass: "asds7ds7d6"
        }
      });
      const mailOptions = {
        from: '"noreply@yourdomain.com" <noreply@yourdomain.com>',
        to: email,
        subject: subject,
        text: url,
        html: htmlToSend
      };
      const info = await transporter.sendMail(mailOptions);
      console.log("Message sent: %s", info.messageId);
      console.log("Preview URL: %s", "https://mailtrap.io/inboxes/test/messages/");
    
    }
    
    0 讨论(0)
  • 2021-01-30 17:51

    There is one easy way to insert variable inside html in nodemailer.

        html:"<p>Your message "+variable1+".Message continueous "+variable 2+"</p>"
    
    0 讨论(0)
提交回复
热议问题