Search code examples
node.jsexpressnodemailer

How do I send a html file using nodemailer


I am sending emails using nodemailer, but I wanna know how to send a static HTML file from a directory.

  let transporter = nodemailer.createTransport({
      host: auth.host,
      port: auth.port,
      secure: auth.secure,
      auth: {
          type: auth.type,
          user: auth.user,
          clientId: auth.clientId,
          clientSecret: auth.clientSecret,
          refreshToken: auth.refreshToken,
          accessToken: auth.accessToken,
          expires: auth.expires
      }
  });

  let mailOptions = {
    from: '"xxxxx',
    to: 'xxxx',
    subject: "xxxx",
    text: `xxxx`,
    html: email.html
  };

Solution

  • You will have to read the file using the fs module.

    const fs = require('fs');
    
    const { promisify } = require('util');
    
    const readFile = promisify(fs.readFile);
    
    async function sendMail() {
        let transporter = nodemailer.createTransport({
          host: auth.host,
          port: auth.port,
          secure: auth.secure,
          auth: {
              type: auth.type,
              user: auth.user,
              clientId: auth.clientId,
              clientSecret: auth.clientSecret,
              refreshToken: auth.refreshToken,
              accessToken: auth.accessToken,
              expires: auth.expires
          }
      });
    
      let mailOptions = {
        from: '"xxxxx',
        to: 'xxxx',
        subject: "xxxx",
        text: `xxxx`,
        html: await readFile('/path/to/file', 'utf8')
      };
    
      // send mail
    }
    

    If the file won't change, you can cache the content.