forwardemail / email-templates

Create, preview (browser/iOS Simulator), and send custom email templates for Node.js. Made for @forwardemail, @ladjs, @cabinjs, @spamscanner, and @breejs.
https://forwardemail.net/docs/send-emails-with-node-js-javascript
MIT License
3.64k stars 339 forks source link

[fix] Unable to use plugin #443

Closed onajourney closed 1 year ago

onajourney commented 1 year ago

Describe the bug

Node.js version: v14.20.0

OS version: Windows 10 Home

Description: Unable to update email information through transporter plugin.

Actual behavior

Changes through plugin are ignored

Expected behavior

Able to make changes to emails content

Code to reproduce

const Email = require('email-templates');
const nodemailer = require('nodemailer');

(async ()=>{

  let testAccount = await nodemailer.createTestAccount();

  // create reusable transporter object using the default SMTP transport
  let transporter = nodemailer.createTransport({
    host: "smtp.ethereal.email",
    port: 587,
    secure: false, // true for 465, false for other ports
    auth: {
      user: testAccount.user, // generated ethereal user
      pass: testAccount.pass, // generated ethereal password
    },
    // Different attempt to try to do the same thing
    // send: (mail, callback) => {
    //   let addresses = mail.message.getAddresses();
    //   callback(null,  { ...mail, addresses: { ...mail.addresses, to: [ { address: 'monkey@email.com', name: 'monkey name' } ] }} );
    // }
  });

  // plugin 
  transporter.use('compile', (mail, callback) => {
    // Original content
    console.log('before', mail.data.html);
    mail.data.to = 'MY@EMAIL.com'
    mail.data.html += 'Additional dev info appended';
    // Shows updated information
    console.log('after', mail.data.html);
    callback();
  });

  const email = new Email({
      message: {
        from: 'test@example.com'
      },
      // comment below to send emails in prod env:
      send: true,
      transport: transporter
  });

  // Ultimately email is sent but does not contain changes
  email
      .send({
        template: 'mars',
        message: {
            to: 'elon@spacex.com'
        },
        locals: {
          name: 'John Doe',
        }
      })
      .then(console.log)
      .catch(console.error);

})();

Checklist

titanism commented 1 year ago

If you want to modify the to, then you need to modify mail.message, not mail.data, see https://nodemailer.com/plugins/create/#compile.

onajourney commented 1 year ago

@titanism It seems the package is actually honoring the changes I made through mail.data at compile - however the preview is not showing those changes.

Not sure how that might be fixed - maybe transport has events you could use to run the preview after changes are made?

Anyways, my issue is resolved.