mailjet / mailjet-apiv3-nodejs

[API v3] Official Mailjet API v3 NodeJS wrapper
https://dev.mailjet.com
MIT License
232 stars 67 forks source link

Error when sending emails using Mailjet and promises #252

Closed antho227 closed 11 months ago

antho227 commented 12 months ago

I get an error when I'd like to send emails using promises. I'm using promises because I have 889 emails to send and I know that I can send up to 50 emails per calls.

My code :

function arraySend(array, locals) {
  var mailjetConnect = mailjet.connect(****username, ****password),
      chunkedArrayMessages = _.chunk(array, 50),
      promises;

  if (process.env.NODE_ENV !== 'dev') {
    promises = chunkedArrayMessages.map((messages) => {
      return mailjetConnect.post('send', { version: 'v3.1' }).request({ Messages: messages });
    });
    return Promise.all(promises).then(function() {
      return Promise.resolve();
    }).catch(function(err) {
      return Promise.reject(err);
    });
  } else {
    return Promise.resolve();
  }
}

Error message :

UnhandledPromiseRejectionWarning: Error: Unsuccessful ... Mailjet

ai-wintermute commented 11 months ago

Hi @icecomagency your approach is a bit incorrect. You're actually trying to send messages one by one and the Messages value you're passing is in the wrong format, that's why you're getting an error. Try to process messages by batches, something like this:

const Mailjet = require('node-mailjet');

const mailjet = Mailjet.apiConnect(
   process.env.MJ_APIKEY_PUBLIC,
    process.env.MJ_APIKEY_PRIVATE,
);

async function arraySend(array, locals) {
    const batchSize = 50;
    let count = 1;
    for (let i = 0; i < array.length; i += batchSize) {
        const batch = array.slice(i, i + batchSize);
         await mailjet
            .post('send', { version: 'v3.1' })
            .request({
                Messages: batch,
            })
             .then((result) => console.log(`Processed batch ${count} of ${Math.round(array.length/batchSize)},
             Messages sent: `, JSON.stringify(result.body))
             )
             .catch((err) => console.log(err));
         // this is just to track the process
         count++;
    }
}

Please let us know if something is unclear.